将参数传递给Angular中的嵌套指令

时间:2015-12-27 14:42:54

标签: angularjs

我试图将参数从父指令传递给子指令,但参数似乎未定义。有没有正确的方法来做到这一点?

}).directive('flipper', function ($timeout) {
return {
    template: '<div class="flipper" ng-class="{big: big}"><div class="inner animated " ng-style="rotatorTop()"><ul><li ng-repeat="app in apps">{{app.name}}</li></ul></div></div>',
    restrict: 'E',
    replace: false,
    scope: {
        apps: "=",
        big: "=",
        sizes: "="
    },
    link: function ($scope, $element, $attrs) {

        // undefined!
        alert($scope.apps);
        ...


    }
};
}).directive('slogan', function ($window) {
return {
    template: '<div class="message"><div class="message-big"><div class="black">{{lines[0]}}<flipper apps="apps" class="big" sizes="flipperSize"></flipper>' +
    '</div><div class="black">{{lines[1]}}</div><div class="black">{{lines[2]}}</div></div></div>',
    restrict: 'E',
    replace: false,
    transclude: true,
    scope: {
        apps: "=",
        lines: "="
    },
    link: function ($scope, $element, $attrs) {
          ...
    }
};
});

1 个答案:

答案 0 :(得分:1)

是的。由于您的代码非常不完整,我已经this simple directive演示了如何将控制器中的值传递给父指令和子指令。

myApp.directive('cdParent', function() {
  return {
    restrict: "AE",
    template: "<div cd-child option=\"option\" text=\"text\">",
    scope: {
      option: "="
    },
    link: function(scope, elem, attrs) {
      console.log("inside parent directive: " + scope.option); // will log the color for the controller
      scope.text = "Hello nested directives";
    }
  }
});

myApp.directive('cdChild', function() { 
  return {
    restrict: "AE",
    template: "<pre style=\"color: {{option}}\">{{text}} ({{option}})</pre>",
    scope: {
      option: "=",
      text: "="
    },
    link: function(scope, elem, attrs) {
      console.log("inside child directive: " + scope.option);
    }
  }
});

另外,link函数不像控制器那样进行依赖注入,因此它的参数应该是scope, element, attrs而不是$scope, $element, $attrs,参数顺序是差异在这里