I am writing an AngularJS directive and would like to bind the ng-model value to an array of objects in the controller. The $render in the directive link I would expect to be fired when anything in the array is changed. In fact, $render is only fired when the reference to the array is changed. Why is this and is this the intended behavior for ngModelController?
Code below demonstrates this behavior and also in this fiddle: http://jsfiddle.net/HandyManDan/RCctF/
<div ng-app="tryApp">
<div ng-controller="MyCtrl">
<div> Bound in controller: {{modelVals[0].val}}</div>
<div> Bound in directive: <span my-dir="" ng-model="modelVals"></span></div>
<button ng-click="lftBtn()">Mod deep</button>
<button ng-click="rtBtn()">Mod ref</button>
</div>
</div>
myApp.controller('MyCtrl', function($scope) {
$scope.modelVals = [{val:'val init'}];
$scope.lftBtn = function() {
$scope.modelVals[0].val = 'val change deep';
};
$scope.rtBtn = function() {
$scope.modelVals = [{val:'val change ref'}];
};
});
myApp.directive('myDir', function() {
return {
restrict: 'A',
priority: 1,
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$render = function() {
element.find('*').remove();
var el = angular.element("<span>" + ngModel.$modelValue[0].val + "</span>)");
element.append(el);
};
}
};
});