[英]$watch for value change from inside angular directive when using isolate scope
我试图找到一种方法来监视对象的属性值的变化,而该对象正在将指令的作用域限定在范围内,而我无法弄清楚我在做什么错。
这是我的指令代码:
.directive('selectService', [function() {
return {
restrict: 'EA',
scope: {
distribution: '='
},
link: function(scope, element, attrs) {
scope.$watch(scope.distribution.name, function(newValue) {
console.log("Changed to " + newValue);
});
因此,说运行时的分发是这样的:
{ name: '', type: 'all' ... }
我想监视$ name属性何时具有值,以便可以在指令中启用选择菜单。 我所做的一切似乎都不起作用。 任何帮助表示赞赏。
只需以通常的方式使用watch即可,在范围上提供一个表示属性的字符串或一个返回要监视值的函数。
scope.$watch('distribution.name', function(newValue) {
console.log("Changed to " + newValue);
});
要在对象distribution
上设置深入监视,请将watch的第三个参数设置为true。 当将scope.distribution.name
提供给watch函数的第一个参数时,它将只是在不正确的scope.distribution.name
值(当时)上设置watch。
演示
angular.module('app', []).controller('ctrl', function($scope) { $scope.distribution = {}; }).directive('selectService', [ function() { return { restrict: 'EA', scope: { distribution: '=' }, link: function(scope, element, attrs) { scope.$watch("distribution.name", function(newValue) { console.log("Changed to " + newValue); }); } } } ])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="ctrl"> <input ng-model="distribution.name">{{distribution.name}} <div select-service distribution="distribution"></div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.