如何在angularjs中将对象字段作为指令参数传递?

时间:2015-04-02 11:25:26

标签: javascript angularjs

我想将对象数组传递给指令,并打印出我在使用该指令的地方确定的字段。

以下是例子:

//directive
app.directive('MyDirective', function() {
  return {
    restrict: 'A',
    templateUrl: 'my-directive.html',
    scope: {
      items: '@',
      field: '@'
    }
  };
});

// my-directive.html template
<div ng-repeat="item in items">{{ item.field }}</div>

我的想法是,我可以将它用于任何这样的对象:

// object arrays
var phones = [{id:1,number:'555-5555'}, {id:2,number:'555-6666'}];
var persons = [{id:1,name:'John'}, {id:2,name:'Jane'}];


// directive usage
<div my-directive items="phones" data-field="???number???"></div>
<div my-directive items="persons" data-field="???name???"></div>

结果应打印出数字和名称。这在Javascript中是否可行?

3 个答案:

答案 0 :(得分:2)

您可以使用'='绑定项目:

.directive('myDirective', function() {
  return {
    restrict: 'A',
    template: '<div ng-repeat="item in items">{{ item[field] }}</div>',
    scope: {
      items: '=',
      field: '@'
    }
  };
})

然后像这样使用它:

<div my-directive items="phones" field="number"></div>

请参阅此plunker

答案 1 :(得分:1)

是的,可以,你可以这样做:

<强>指令:

myApp.directive('myDirective', function() {
    return {
        restrict: 'A',
        template: '<div ng-repeat="item in items">{{ getItemField(item) }}</div>',
        scope: {
          items: '=',
          field: '@'
        },
        link: function(scope, element, attr) {
            scope.getItemField = function (item) {
                return item[scope.field];
            };
        }

      };

<强> HTML:

<div my-directive items="phones" data-field="number"></div>
<div my-directive items="persons" data-field="name"></div>

Fiddle

答案 2 :(得分:0)

这不是一个指令,可能你正在寻找的指令是ng-repeat:

var phones = [{id:1,number:'555-5555'}, {id:2,number:'555-6666'}];
var persons = [{id:1,name:'John'}, {id:2,name:'Jane'}];

<li ng-repeat="phone in phones">{{phone.number}}</li>

<li ng-repeat="person in persons">{{person.name}}</li>