javascript - AngularJS. Adding $watch to the particular model -
i new angularjs , don't know how add $watch
particular model. when going through angularjs tutorial facing issue. mentioned doubt in comments part. please go through this.
(function(angular) { angular.module('controllerasexample', []) .controller('settingscontroller1', settingscontroller1); function settingscontroller1() { this.name = "john smith"; this.contacts = [ {type: 'phone', value: '408 555 1212'}, {type: 'email', value: 'john.smith@example.org'} ]; } //how add $watch ng-model 'settings.name' /*$scope.$watch("settings.name", function(oldval, newval){ console.log(oldval + " + " + newval); });*/ settingscontroller1.prototype.greet = function() { console.log(this.name); }; })(window.angular);
html code..
<body ng-app="controllerasexample"> <div id="ctrl-as-exmpl" ng-controller="settingscontroller1 settings"> <label>name: <input type="text" ng-model="settings.name"/></label> <button ng-click="settings.greet()">greet</button><br/> </div> </body>
here check link
basically, need inject $scope
context. stated in answer.
function settingscontroller1($scope) { this.name = "john smith"; this.contacts = [ {type: 'phone', value: '408 555 1212'}, {type: 'email', value: 'john.smith@example.org'} ]; $scope.$watch(angular.bind(this, function () { return this.name; }), function (newval, oldval) { console.log('name changed ' + newval + ', old value = ' + oldval); }); }
notice $scope
being passed function controller , angular.bind(this
tells watcher right context.
working example: http://plnkr.co/edit/hr0dtphdbsf2xxufmwft?p=preview
Comments
Post a Comment