I have the following markup:
<div ng-controller="DataController as vm">
<div ng-repeat="name in vm.users track by $index">
{{name}}
</div>
<form name="form" validation="vm.errors">
<input validator ng-model="vm.name" name="vm.name" placeholder="name" type="text" />
<a href="#" ng-click="vm.add(vm.name)">Add</a>
</form>
</div>
I have the following controller:
function DataController($scope) {
var vm = this;
vm.name = "Mary";
vm.users = ["Alice", "Peter"];
vm.errors = 1;
vm.add = function(name) {
vm.errors++;
vm.users.push(name);
}
}
Every time I add a user I increase the value of errors.
I need to watch this variable inside a directive so I have:
app.directive("validation", validation);
function validation() {
var validation = {
controller: ["$scope", controller],
restrict: "A",
scope: {
validation: "="
}
};
return validation;
function controller($scope) {
this.errors = $scope.validation;
}
}
app.directive("validator", validator);
function validator() {
var validator = {
link: link,
replace: false,
require: "^validation",
restrict: "A"
};
return validator;
function link(scope, element, attributes, controller) {
scope.$watch(function() {
return controller.errors;
}, function () {
console.log(controller.errors);
});
}
The console.log shows the initial value but not new values:
https://jsfiddle.net/qb8o006h/2/
If I change vm.errors to an array, add the values, and watch its length then it works fine: https://jsfiddle.net/nprx63qa/2/
Why is my first example does not work?