How to subscribe on property change when using controller as
syntax?
controller(\'TestCtrl\', function ($
Here is how you do this without $scope (and $watch!) Top 5 Mistakes - Abusing watch
If you are using "controller as" syntax, it's better and cleaner to avoid using $scope.
Here is my code in JSFiddle. (I am using a service to hold the name, otherwise the ES5 Object.defineProperty's set and get methods cause infinite calls.
var app = angular.module('my-module', []);
app.factory('testService', function() {
var name = 'Max';
var getName = function() {
return name;
}
var setName = function(val) {
name = val;
}
return {getName:getName, setName:setName};
});
app.controller('TestCtrl', function (testService) {
var vm = this;
vm.changeName = function () {
vm.name = new Date();
}
Object.defineProperty(this, "name", {
enumerable: true,
configurable: false,
get: function() {
return testService.getName();
},
set: function (val) {
testService.setName(val);
console.log(vm.name);
}
});
});