I am creating a demo application with two controllers communicating through a service containing some data. This is a kind of contact book. The user can edit the selected person from the list.
The data is stored in an array of objects, and I use a custom directive to perform some manipulation of the text properties of these objects.
The problem is that the text displayed in the list using the custom directive is not updated when the model changes (when entering anything in the name fields), but the text that is placed using {{}} changes when entering text.
Here is an example showing the problem:
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>
Working demo: http://cssdeck.com/labs/ejnhuqf9
Perhaps the problem is with $ watch, but everything looks fine. Any suggestions?
PS In a real application, I need to use the directive to perform more complex text manipulations than just concatenation.