【问题标题】:How to pass a function to transcluded scope from a controller (angular 1.3)?如何将函数从控制器(角度 1.3)传递到嵌入范围?
【发布时间】:2015-05-05 12:18:37
【问题描述】:

我创建了一个简单的可重用集合容器作为具有隔离范围的指令,transclude 选项设置为 true。

app.directive('itemWrapper', function() {
  return {
    template: '...',
    replace: true,
    transclude: true,
    restrict: 'E',
    scope: {
      name: '=',
      isExpanded: '='
    }
  };

});

还有一个列表视图指令,我想从控制器中传递一个函数来处理列表项的点击

app.directive('listItem', function() {
      return {
        template: '...',
        replace: true,
        restrict: 'E',
        scope: {
          item: '=',
          action: '&'
        },
        link: function(scope, elm, attrs){
          scope.performAction = function(val){
            action({'data': val});
          };
        }
      };
});

我的 html 块看起来如下:

<collection-wrapper name='item.name' is-expanded='item.visible'>
  <list-item item='item' action='log(data)'></list-item>
</collection-wrapper>

但是当我点击链接时,我得到一个参考错误,说action 没有定义。问题是,如何将一个函数从控制器传递给这个指令?据我了解,嵌入范围是孤立范围的孩子,这是我无法克服的障碍!

这是Plunkr。

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope angularjs-ng-transclude


    【解决方案1】:

    action 是作用域上的一个方法。你需要说:

    scope.action({'data': val});
    

    http://plnkr.co/edit/gt6BgCpZ9qmOEJ8yS4UD?p=preview

    【讨论】:

    • 该死的......我一直在无缘无故地忽略指令中的“范围”。谢谢。
    【解决方案2】:

    根据您的说法,“从控制器传递函数意味着从控制器启动函数,或者您希望从嵌入的内容内部触发函数??

    【讨论】:

    • 在嵌入内容中调用函数。
    • 你用来分配指令内方法引用的方法是绝对完美的,但是由于引用被分配给孤立的范围变量,“范围”有在调用启动期间沿方法添加前缀.. "scope.action({'data':val});" 我想这可以正常工作...!!干杯。查看this link 以进一步了解它..
    猜你喜欢
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    相关资源
    最近更新 更多