简体   繁体   English

在angular中,是否可以在运行控制器之前让指令将变量添加到作用域?

[英]In angular, is it possible to have a directive add a variable to the scope before the controller is run?

I'm setting up a directive which can't have an isolated scope because there are going to be other directives (which are 3rd party) which are already using it. 我正在设置一个不能具有孤立作用域的指令,因为将会有其他已经在使用它的指令(属于第三方)。 I need to get the reference of a third party object and pass it to the controller as a variable. 我需要获取第三方对象的引用,并将其作为变量传递给控制器​​。 How can I do this? 我怎样才能做到这一点?

angular.module('myModule')
    .directive('objectSync', ['$thirdParty', function ($thirdParty) {
    return {
      compile: function() {
          return {
              pre: function(scope, element, attrs) {
                  var thirdPartyObject = $thirdPartyObject.getCurrentScopeObject();
                  scope[attrs.objectSync] = thirdPartyObject;
              }
          };
       }
    };
}]);

And this is the html: 这是html:

<third-party-directive
    sync-object-to-controller="objectToSync">

When I do this, objectToSync never makes it to the controller's scope. 当我这样做时,objectToSync永远不会进入控制器的范围。 But if I set up a container object in the scope: $scope.containerObject = {} , in the directive instead of adding it right to the scope I add it there: scope.containerObject[attrs.objectSync] = thirdPartyObject; 但是,如果我在范围内设置了一个容器对象: $scope.containerObject = {} ,而不是在指令中将其添加到范围中,则将其添加到该范围中: scope.containerObject[attrs.objectSync] = thirdPartyObject; , then it makes it through, but I can only call it/attach listeners to it using watch: $scope.$watch(function(){ return $scope.containerObject; } ... ,那么它就可以通过,但是我只能使用watch来调用它/为其附加侦听器: $scope.$watch(function(){ return $scope.containerObject; } ...

So how can I pull an object from a third party from within the scope of the third party directive and pass it into the root of the controller's scope with a name specified in my own directive before the controller runs? 那么,如何在控制器运行之前从第三方指令范围内的第三方提取对象,并将其传递给控制器​​范围的根,并使用我自己的指令中指定的名称?

You need to receive the parameter passed to third-party-directive. 您需要接收传递给第三方指令的参数。

angular.module('myModule')
    .directive('objectSync', ['$thirdParty', function ($thirdParty) {
        return {
            scope : {syncObjectToController : '='} //this receives the parameter
                //the hyphen separated name gets converted to camel casing
            compile: function() {
            return {
                pre: function(scope, element, attrs) {
                    //now you can directly use the third party object here directly
                    var thirdPartyObject = scope.syncObjectToController
                }
            };
         }
     };
}]);

Read more about it in angular's documentation of directives. 在angular的指令文档中了解有关它的更多信息。

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

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