简体   繁体   English

从Javascript调用AngularJS隔离范围函数

[英]Calling an AngularJS isolated scope function from Javascript

We are slowly porting an application to use Angular. 我们正在慢慢移植应用程序以使用Angular。 I have an angular module and a directive that attempts to tie some functionality to an HTML element. 我有一个angular模块和一个指令,试图将某些功能绑定到HTML元素。

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: 给定一些html:

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

And some javascript: 和一些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. 我希望看到“我想看到这个,elementId:e2”,但我不是。 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?). 当我使用Firebug检查javascript时,我看到测试对象引用的是主作用域,而不是我期望的隔离作用域(希望吗?)。 I can tell this because test.foo has the value "BAR", not "xxxx". 我可以这样说是因为test.foo的值为“ BAR”,而不是“ 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. 此外,我在Firebug中看到$$ childHead对象是我想要的内部作用域,因此我可以肯定,除了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. 整个团队对于Angular来说还相对较新,如果我错过了明显的事情,请原谅我。 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: 我需要添加scope:true,这样我就可以了:

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

to my directive definition. 我的指令定义。 PSL set me on the right path; PSL使我走上了正确的道路; 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 http://plnkr.co/edit/w7OGtRgtys7AeRtWH9qe?p=info

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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