【问题标题】:AngularJs How to pass the complex object in directivesAngularJs如何在指令中传递复杂对象
【发布时间】:2014-01-26 17:57:43
【问题描述】:

我有这个指令:

amDirective.directive('directiveList', function() {
    return {
        restrict: 'A',
        scope: {
           'event': '&onEvent'
        },
        transclude: true,
        templateUrl: ''
    };
});

在我的页面html中

<div data-dy-directive-list data-elements="elements" on-event="listItemClicked(item)"></div>

在我的指令模板 html 中

 <table class="table" data-ng-show="elements!=null && elements.length>0">

    <tr  data-ng-repeat="element in elements">                     
        <td><span  data-ng-click="event(element)">{{element.title}}</span></td>           
    </tr>
    <tr></tr>   
</table>

如何在我的指令中传递复杂对象“项目”?

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    从您的指令(控制器或链接函数)中,您将调用:scope.event({item: item}),将命名映射从参数名称传递到值以提供给回调。

    例子:

    amDirective.directive('directiveList', function() {
        return {
            restrict: 'A',
            scope: {
               'event': '&onEvent'
            },
            transclude: true,
            templateUrl: '',
            link: function(scope, element, attrs) {
              element.bind('click', function() {
                scope.event({ item:  { hello: 'world', x: 3 } });
              });
            }
        };
    });
    

    用法:

    <a directive-list on-event="myHandler(item)">Click Me<a>
    

    Here's an example plnkr.

    见:Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

    【讨论】:

      【解决方案2】:

      angular 指令使用 '&' 绑定到父范围表达式。 这意味着当指令内部发生事件时,您的指令将评估它。

      示例

      app.directive('directiveList', function() {
          return {
              restrict: 'A',
              scope: {
                 'event': '&onEvent'
              },
              link: function(scope){
                var myItem = {}
                scope.event = function(item) {
                element.bind('click', function(){
                  scope.event({item: myItem})
                })
              }
          };
      });
      

      如果您想从父范围引发事件并让您的指令知道您应该使用“=”

      示例

      app.directive('directiveList', function() {
          return {
              restrict: 'A',
              scope: {
                 'event': '=onEvent'
              },
              link: function(scope){
      
                scope.event = function(item) {
                   // manipulate item
                   return "something";
                }
      
              }
          };
      });
      

      【讨论】:

        猜你喜欢
        • 2013-09-27
        • 2013-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多