$watch ng 격리 범위를 사용하는 내부 지시어 모델
링크 기능 안에서 모델 값을 관찰하려고 합니다.
scope.$watch(attrs.ngModel, function() {
console.log("Changed");
});
컨트롤러 내에서 모델 값을 변경해도 $watch 기능이 트리거되지 않습니다.
$scope.myModel = "ACT";
$timeout(function() {
$scope.myModel = "TOTALS";
}, 2000);
바이올린: http://jsfiddle.net/dkrotts/BtrZH/4/
내가 뭘 놓쳤지?
감시하고 있는 $modelValue를 반환하는 함수를 감시해야 합니다.
다음 코드는 기본적인 예를 나타냅니다.
app.directive('myDirective', function (){
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
scope.$watch(function () {
return ngModel.$modelValue;
}, function(newValue) {
console.log(newValue);
});
}
};
});
문제는 네가$watch입력attrs.ngModel"myModel"과 동일합니다.범위에 "myModel"이 바인딩되어 있지 않습니다.하고 싶다$watch"모델"그것이 당신의 지시의 범위에 속박되어 있는 것입니다.http://jsfiddle.net/BtrZH/5/ 를 참조해 주세요.
적절한 방법은 다음과 같습니다.
app.directive('myDirective', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$render = function () {
var newValue = ngModel.$viewValue;
console.log(newValue)
};
}
};
});
그 외의 방법은 다음과 같습니다.
app.directive('myDirective', function (){
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
attrs.$observe('ngModel', function(value){ // Got ng-model bind path here
scope.$watch(value,function(newValue){ // Watch given path for changes
console.log(newValue);
});
});
}
};
});
이렇게 하면 그와 같은 바인드로 가치의 변화를 청취할 수 있습니다.
이것은 @Martin Vellez에 대한 @Martin Vellez의 답변의 연장선입니다(또, 아직 코멘트를 할 수 없기 때문에, 이쪽이 적절하지 않다면 죄송합니다).
어떤 버전의 Angular OP를 사용했는지 모르겠지만, 적어도 공식 문서에서는 Angular #1.2+에 https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$render, $http://http://http://http://http://http:/http:/http:/h
보기를 업데이트해야 할 때 호출됩니다.ng-model 디렉티브 사용자는 이 메서드를 구현할 것으로 예상됩니다.
$render() 메서드는 다음과 같은 경우에 호출됩니다.
$rollbackViewValue()가 호출됩니다.뷰 값을 마지막으로 커밋된 값으로 롤백하면 $render()가 호출되어 입력 제어가 갱신됩니다.ng-model이 참조하는 값은 프로그래밍 방식으로 변경되며 $modelValue와 $viewValue 모두 이전과 다릅니다.ng-model은 딥 워치를 하지 않기 때문에 $render()는 $modelValue 및 $viewValue 값이 실제로 이전 값과 다른 경우에만 호출됩니다.
디렉티브에서 ngModel을 $watch 하는 올바른 방법은 ngModel을 요구하고 ngModelController를 주입하는 링크 함수를 구현하는 것이라고 해석합니다.그런 다음 $render-on-change($watch)에 내장된 ngModel API를 사용합니다.
두 가지 방법이 있습니다.
) 1) ㄴㄴ데 를 사용하시면 .$attrs.[any_attribute]합니다.
2) 2 Ways binding variable로 scope를 분리하여 Listener를 설정할 수 있습니다.더 필요하시면 여기 멋진 기사가 있습니다.
언급URL : https://stackoverflow.com/questions/14693052/watch-ngmodel-from-inside-directive-using-isolate-scope
'source' 카테고리의 다른 글
| SQL Recoverable예외:I/O 예외:접속 리셋 (0) | 2023.03.28 |
|---|---|
| mvn spring-boot 종료: run does stop tomcat (0) | 2023.03.23 |
| 리액트 라우터 스위치의 동작 (0) | 2023.03.23 |
| 오류: 스프링 컨트롤러의 @WebMvcTest 실행 시 @SpringBootConfiguration을 찾을 수 없습니다. (0) | 2023.03.23 |
| Wordpress 플러그인 프로그램 설치 및 활성화 (0) | 2023.03.23 |