2017-10-18 70 views
0

我想使用綁定到對象的自定義指令,但我想指定模板中使用的字段。以前,我使用的是{{item.Name}},但我想綁定到任何對象,指定顯示字段。指令模板中的動態字段(angularjs)

這是我

var foo = function() { 
    return { 
     restrict: 'E', 
     scope: { 
      items: '=' 
     }, 
     template: 
     "<div class='holder'>" 
      + "<a data-ng-repeat='item in items' data-ng-click='myClick(item)'><i class='fa fa-times'/>{{item.Name}}</a>" 
      + "</div>", 


     controller: function ($scope) {......} 
     } 
} 

我想這樣做:

var foo = function() { 
    return { 
     restrict: 'E', 
     scope: { 
      items: '=', 
      display_field: 'Name', 
      icon_field: 'fa fa-times', 
     }, 
     template: 
     "<div class='holder'>" 
      + "<a data-ng-repeat='item in items' data-ng-click='myClick(item)'><i data-ng-class='{{item.icon_field}}'/>{{item.display_field}}</a>" 
      + "</div>", 


     controller: function ($scope) {......} 
     } 
} 

凡display_field和圖標可以這樣規定:

<foo items="myItems" display_field="OtherProperty" icon-field="iconProperty" /> 

小提琴: http://jsfiddle.net/1L7tdd1p/

回答

1

你就近了。記住角表達式是Javascript表達式的子集。要使用動態屬性名稱使用括號記號訪問屬性:

{{ item[display_field] }} 

任何值可以是對象的關鍵,而不僅僅是字符串。括號表示法允許您使用任何表達式作爲重點訪問對象的屬性:

var obj = {}; 
 
obj[1] = 'a'; 
 
obj.asdf = 'b'; 
 
obj[{}] = 'c'; 
 
console.log(obj[1], obj['asdf'], obj[{}]);

此外,我想你是誤會了scope選項的目的。 scope選項允許您指定一組綁定,您的指令將從您使用它的元素中獲取,以及此綁定的類型。您無法使用它設置默認值。看看Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

var myApp = angular.module('myApp', []); 
 

 
//myApp.directive('myDirective', function() {}); 
 
//myApp.factory('myService', function() {}); 
 

 
function MyCtrl($scope) { 
 
    $scope.name = 'Superhero'; 
 
} 
 

 
myApp.directive('foo', function() { 
 
    return { 
 
    restrict: 'E', 
 
    scope: { 
 
     items: '=', 
 
     prop: '@' // this declared a 
 
    }, 
 
    template: " <a data-ng-repeat='item in items'><br/>{{item[prop]}}</a>", 
 

 
    controller: function($scope) {} 
 
    } 
 

 
}); 
 

 
myApp.controller("appController", function($scope) { 
 
    $scope.Items = [{ 
 
    "id": 1, 
 
    "name": "aaaa" 
 
    }, { 
 
    "id": 2, 
 
    "name": "bbbb" 
 
    }] 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script> 
 
<div ng-app='myApp' ng-controller="appController"> 
 
    <foo items="Items" prop='name'></foo> 
 
</div>

+0

感謝您的快速幫助。由於某種原因,只是不起作用。它只是顯示空白。即使我有一個名爲display_field的文字字段。我試圖讓它在小提琴中工作http://jsfiddle.net/1L7tdd1p/ – NetHawk

+0

我複製並修改了你的小提琴。看看我的編輯。 – nicooga

+0

謝謝!我想我很接近。最後一點我的問題是我需要使用@而不是=。 – NetHawk