$watch with controller as in Angularjs

Hello everybody,

today I want to write few words about interesting case which I faced.

Recently my company asked me to follow code convention of John Papa according to which I shouldn't use in my controller code $scope, but instead use vm. 

In code it looks like this:

angular
    .module('app')
    .controller(cnt, mosController);//register
morningStarController.$inject = ['$scope'];

and continuation:

function mosController($scope) {
    var vm = this;     var settings = {};     vm.settings = jsonSettings;

Then question arise, how to use $watch or how to track variable?

Below goes way of implementing it with help of $scope:

var variable = 5;
$scope.variable = variable;
$scope.$watch('variable', function(newValue, oldValue) {
    //some reaction for changes in variable
});

but if you decide to use  

var vm = this;

then you'll lose the way of working with $scope. How to deal with this situation. I propose following way. 

1. Give to your controller as some name. 

2. bind $scope.$watch to given name. 

3. use ng-model for binding

For example I implemented points 1 and 2 in the following way:

1. Named mosController as msc:

<body ng-controller="mosController as msc">

2. Binded with $scope.$watch as this:

$scope.$watch('msc.variable', function (newValue, oldValue) {
        modifyCaption();
    });

3.  and look how I binded:

<input type="number" id="num" ng-model="msc.variable" min="0.1" max="2" step="0.01" />

That's pretty it. Hope it can be useful for somebody, especially if you want to inject your $scope with avoiding direct passing it into function.

No Comments

Add a Comment