简体   繁体   中英

AngularJS - How can I read the value of a model defined in an isolate scope?

I need to use an isolate scope in a directive; I am trying to read the value of a model specified in an attribute. So my directive is used like this:

<div mydirective="" mydirective-data="MyJson" />

In a controller, I am assigning a value to $scope.MyJson . My directive should pick it up, but doesn't.

app.directive('mydirective', function() {
   return {
     restrict: 'A',
     scope: {
       data: '&mydirectiveData',
     },
     link: function(scope, element, attrs) {
         console.log(scope.data);
         }
     }
   }
);

Note that I need to use an isolate scope. I have also created a JSFiddle with this problem in it. (Remember to open the console)

I expect to see the value of MyJson , but am seeing nothing instead.

Replace the & within the scope with =, and it would get you the object. If you are using & use scope.data()

I would write my directive this way:

app.directive('mydirective', function() {
   return {
     restrict: 'A',
     scope: {
       mydirectiveData: '='
     },
     link: function(scope, element, attrs) {
         console.log(scope.mydirectiveData);
         }
     }
   }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM