1

My directive has an isolated scope and it receives object from the enclosing controller as an attribute.

app.directive('details', function() {
        return {
            restrict : 'E',
            scope : {
                device : '=device',
                .
                .
                .
            },
            templateUrl : '/details.html',
            link : function(scope, element, attrs) {
                attrs.$observe('device', function(value) {
                ...
                });
            }
        };
    });

And in HTML:

<details device='ctrlAlias.device' ...>

I read somewhere that if I want to check for changes in attribute, I need to use $observe function. However, most examples I saw use $observe on primitive values only.

I wonder how would I $observe a property of device, say device.exist (a boolean) and device.id (a string) within the attrs.$observe?

oikonomiyaki
  • 7,691
  • 15
  • 62
  • 101

1 Answers1

3

You should use $watch

Registers a listener callback to be executed whenever the watchExpression changes.

Whereas, $observe is a method on the Attributes object

Observes an interpolated attribute.

Code

scope.$watch(function() {
    return scope.device
}, function(newValue, oldValue) {    
}, true);

Visit AngularJS : Difference between the $observe and $watch methods for more details.

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • see this post for more details on the difference between `$watch` and `$observe`. http://stackoverflow.com/questions/14876112/difference-between-the-observe-and-watch-methods – morloch Nov 04 '14 at 11:01
  • @Satpal I coded `function(newValue, oldValue) {if (typeof oldValue === "undefined") && (newValue.exist == true) {...}}` but I get undefined on the property. – oikonomiyaki Nov 04 '14 at 11:21
  • @menorah84, What is the expected value `ctrlAlias.device`? – Satpal Nov 04 '14 at 11:30
  • @Satpal It's a nested object. `exist` is a first-level property. – oikonomiyaki Nov 04 '14 at 11:34