Watching non-existant properties
by rgthree
HTML
<script src="https://code.angularjs.org/1.4.3/angular.min.js"></script>
<div ng-app="app" ng-controller='AppCtrl'>
<test></test>
</div>
JavaScript
var app = angular.module('app', []);
app.controller('AppCtrl', function ($scope) {});
var testCtrl = function($scope, $timeout) {
console.log('----');
this.person = {};
this.changeCount = 0;
this.scope_ = $scope;
this.$timeout_ = $timeout;
this.scope_.$watch(function() {
return this.person;
}.bind(this), this.onFirstNameChange.bind(this));
this.fakeFetch();
};
testCtrl.prototype.fakeFetch = function() {
this.$timeout_(function() {
this.person = {
firstName: 'Ben',
lastName: 'Jammin',
};
console.log('fakeFetch Done', this);
}.bind(this), 2000);
console.log('fakeFetch Start');
}
testCtrl.prototype.onFirstNameChange = function() {
this.changeCount++;
console.log('onFirstNameChange');
}
app.directive('test', function() {
return {
restrict: 'E',
replace: true,
template: '<div><input ng-model="testCtrl.person.firstName" /><br>First Name:{{testCtrl.person.firstName}}<br><br>Changes: {{testCtrl.changeCount}}</div>',
bindToController: true,
controller: testCtrl,
controllerAs: 'testCtrl'
};
});