Francisc
Francisc

Reputation: 80415

Passing object from parent controller to isolated scope child directive

I have an object that I want watched inside a directive.
The directive has isolated scope and the object comes from a parent controller.

DOM:
<div hello-directive obj-to-track="{{myObj}}"></div>

Directive JS:

scope:{
   objToTrack:'@'
},
link:function(scope,element,attrs){
   scope.$watch(function(newValue){
      //Inside here, newValue is a JSON string
      //So is scope.objToTrack
   });
}

Is there anyway to get an actual object from the parent controller besides JSON.parse()
Thanks.

Upvotes: 7

Views: 5781

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40298

Just use the "=" binding:

scope:{
    objToTrack: "="
}

Watch it as usual:

scope.$watch("objToTrack", function(newval, oldval) {
    ...
});

Use it as:

<div hello-directive obj-to-track="myObj"></div>

Upvotes: 8

Related Questions