AngularJS自定义指令$watch不工作
AngularJS custom directive $watch not working
我正在创建一个演示应用程序,其中两个控制器通过包含一些数据的服务进行通信。这是一种通讯录。用户可以编辑列表中的选定人员。
数据存储在对象数组中,我使用自定义指令对该对象的文本属性执行一些操作。
问题是,使用自定义指令在列表中呈现的文本在模型更改时(在名称字段中键入内容时)不会更新,而使用{{}}放置的文本在键入时会更改。
以下是一个显示问题的示例:
js
var contacts = angular.module('contacts', []);
contacts.service('database', ['$rootScope', function ($rootScope) {
return {
db : [
{person:{fName:"John", lName:"Williams"}, phone:"11111111111"},
{person: {fName:"Sara", lName:"Lewis"}, phone:"222222222"},
{person: {fName:"Lana", lName:"Watson"}, phone:"33333333333"},
{person: {fName:"John", lName:"Smith"}, phone:"4444444444"}
],
selectedPerson : null,
setSelected : function (i) {
this.selectedPerson = i;
$rootScope.$broadcast('selected');
}
}
}]);
contacts.controller("listCtrl", function($scope, database) {
$scope.list = database.db;
$scope.getSelected = function() {
return database.selectedPerson;
};
$scope.setSelected = function(i) {
database.setSelected(i);
};
});
contacts.controller("editorCtrl", function($scope, database) {
$scope.editing = database.selectedPerson;
$scope.$on('selected', function(event) {
$scope.editing = database.selectedPerson;
});
});
contacts.directive('personName', function() {
return {
restrict: 'AEC',
scope:{
personName: '='
},
link: function(scope, elem, attrs) {
scope.$watch(function(){return scope.personName;}, function(obj) {
var fullName = obj.fName + " " + obj.lName;
elem.text(fullName);
});
}
};
});
html
<div ng-app="contacts">
<div class='list' ng-controller="listCtrl">
<div ng-repeat="i in list"
ng-click="$parent.setSelected(i)"
ng-class="{'sel': ($parent.getSelected() === i)}">
<span person-name="i.person"></span>, {{i.phone}}
</div>
</div>
<div class='edit' ng-controller="editorCtrl">
First name: <input type="text" ng-model='editing.person.fName'> <br>
Last name: <input type="text" ng-model='editing.person.lName'> <br>
Phone: <input type="text" ng-model='editing.phone'> <br>
</div>
</div>
工作演示:http://cssdeck.com/labs/ejnhuqf9
也许问题出在$watch上,但一切似乎都很好。有什么建议吗?
附言:在实际应用程序中,我需要使用该指令来进行比串联更复杂的文本操作。
将$watch(objectEquality)的第三个参数设置为true:
scope.$watch(function(){return scope.personName;}, function(obj) {
var fullName = obj.fName + " " + obj.lName;
elem.text(fullName);
}, true);
您可能需要将属性的名称更改为person,以提醒自己它是整个对象,而不仅仅是字符串名称。
相关文章:
- 为什么AngularJS$scope.watch()在我告诉它监视数组时会停止工作
- 使用服务跟踪用户状态并使 $watch() 正常工作
- AngularJS - $watch无法按预期工作
- AngularJS$watch在if块中不工作
- angularJS$watch在使用控制器更新数据时不在指令中工作
- Greasemonkey脚本停止工作,出现错误:unsafeWindow.document.watch不是函数
- Angular:控制器和指令之间的共享数据.$watch是如何工作的
- $watch不能在其他控制器的变量上工作
- Angularjs: $watch不能在ngTable的控制器中工作
- 使用grunt-contrib-watch对两个目录进行深度的单向同步.代码可以工作,但是grunt-contrib-w
- Angularjs $watch无法正常工作
- Ionic, AngularJs:指令属性$watch在视图被渲染后停止工作
- 当grunt-contrib-watch与grunt-express结合使用时,浏览器负载不工作
- 为什么$watch()不能工作?
- Gulp-inject不能和gulp-watch一起工作
- AngularJS自定义指令$watch不工作
- ng-单击值更改 + $scope.watch 绑定无法正常工作
- $scope上的ng类.$watch不工作在第二次点击
- $watch不能在Angular Modal中工作
- $watch不能与数据模型工厂一起工作