angular-styleguide icon indicating copy to clipboard operation
angular-styleguide copied to clipboard

$watch from example with "controller as" syntax not working

Open RealJTG opened this issue 10 years ago • 3 comments

https://github.com/johnpapa/angular-styleguide#style-y032

    $scope.$watch('vm.title', function(current, original) {
        $log.info('vm.title was %s', original);
        $log.info('vm.title is now %s', current);
    });

While this appears to be a trivial synthetic example, $scope.$watch('vm.username', function() {...}) simply not working for me (according to docs it should).

But it works with function call like this

    $scope.$watch(function (){return vm.username;}, function (current, original) {
        ...
    });

What's actually happening here? Example http://plnkr.co/edit/XXWqT5we26o1jgwxdjuV?p=preview

RealJTG avatar Feb 19 '16 14:02 RealJTG

First off your example is a string....

2nd example is a function that returns string

EricDeCoff avatar Feb 19 '16 15:02 EricDeCoff

When using the srting version, the expression is parsed and the resulting function tries to access $scope.vm.username. But in your template, you are using ... as ctrl, so the controller is aliased on $scope as ctrl not vm.

That's why it is not a good idea (imo at least), to use the string version, because it couples the implementation and the consumption of the controller. I.e. at the time you define your controller, you don't know where it's going to be used and how the consumer of the controller will choose to alias it (e.g. there might be other controllers aliased as vm that the template needs access to and your controller has to be aliased as something else).

It's always safer to use the function version.

gkalpak avatar Feb 19 '16 15:02 gkalpak

@gkalpak oh I see, kinda unobvious. Thanks.

RealJTG avatar Feb 19 '16 16:02 RealJTG