简体   繁体   中英

Calling an AngularJS isolated scope function from Javascript

We are slowly porting an application to use Angular. I have an angular module and a directive that attempts to tie some functionality to an HTML element.

angular.module('myApp', [ ])

  .controller('myCtrl', function($scope){
    $scope.someFunction = function(){return "Not what I want to see.";};
    $scope.foo = "BAR";
  })

  .directive('myDirective', function(){
    return {
      restrict: 'EA',
      transclude: true,
      template: '<div><p>Here is some template html.</p></div>',
      link:{ post:function(scope, element, attrs){
               var elementId = attrs.myId;
               scope.someFunction = function(){return "I want to see this, elementId: " + elementId;};
               scope.foo = "xxxx";
             }
      }
    };
  });

Given some html:

...
<myDirective my-id="e1"></myDirective>
<myDirective my-id="e2"></myDirective>
<myDirective my-id="e3"></myDirective>
...

And some javascript:

...
var test = angular.element(document.getElementById("e2") ).scope();
alert(test.someFunction());
...

I would expect to see "I want to see this, elementId: e2", but I am not. When I inspect the javascript using Firebug, I see that the test object is referencing the main scope, not the isolated scope as I would expect (hope?). I can tell this because test.foo has the value "BAR", not "xxxx". Additionally, I can see in Firebug that the $$childHead object is the inner scope that I want, so I'm pretty certain there has to be a way to get to it besides something like test.$$childHead. Is there a proper way to do this?

The entire team is still relatively new to Angular, forgive me if I've missed something obvious. I realize this might not be the "Angular way" (any comments welcome), but it fits our present migration strategy and needs. Thanks in advance.

I needed to add scope:true, so that I have this:

return {
  restrict: 'EA',
  transclude: true,
  scope: true,
  ...
};

to my directive definition. PSL set me on the right path; I was thinking the scope passed in to the linker was unique to each element. Here's an example. http://plnkr.co/edit/w7OGtRgtys7AeRtWH9qe?p=info

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