[英]Access Angular Factory from Directive Scope
我對Angular還是很陌生,所以也許這不是解決問題的最佳方法。 我正在嘗試從名為topDevices
,范圍的指令訪問名為Devices
的工廠。
topDevices.js
:
app.directive('topDevices', function() {
return {
restrict: 'E',
scope: {
count: '@',
sortKey: '@',
devices: Devices.sortByKey(this.count, this.sortKey)
},
templateUrl: 'app/directives/topDevices.tpl.html'
}
});
這通常是不允許的,還是不好的做法/方法? Devices
包含使用Devices.all()
的設備列表,但我還有一個Devices.sortByKey(count, key)
函數,用於返回按特定鍵排序的有限設備集。
編輯:更多信息
這樣做的目的是創建一個模板,該模板可以按某些X指標列出例如前5名設備。 模板是這樣的:
<h3>Top {{ count }} by {{ sortKey }}</h3>
<table class="table table-bordered table-condensed table-striped table-hover">
<tbody>
<tr ng-repeat="device in devices">
<td>{{ device.id }}</td>
<td>{{ device.name }}</td>
<td>{{ device[sortKey] }}</td>
</tr>
<tr ng-show="!devices.length">
<td colspan="3">No device info available</td>
</tr>
</tbody>
</table>
如果這是Angular工廠,則可以將其作為依賴項傳遞給指令:
app.directive('topDevices', function(Devices) {...})
這樣,您就可以與正在使用的具體實例分離
另一方面,如果您希望能夠傳遞sortByKey()方法,並在指令的隔離范圍內使用它,則應使用“&”或“ =”值定義一個范圍屬性。
使用´=´可以創建兩種方式的數據綁定,並且最容易掌握:
app.directive('topDevices', function() {
return {
restrict: 'E',
scope: {
count: '@',
sortKey: '@',
sort: '='
},
templateUrl: 'app/directives/topDevices.tpl.html'
},
link: function(scope) {
scope.sort(scope.count, scope.sortKey);
}
});
指令的link
方法在創建時執行
然后在使用指令的地方:
<top-devices sort="ctrl.sortByKey"></top-devices>
ctrl是controller中的控制器作為語法,您可以將工廠方法附加到controller
// inside a controller
this.sortByKey = function(count, sortKey) {
return Device.sortByKey(count, sortKey);
}
我將嘗試使用'&'進行解釋:
app.directive('topDevices', function() {
return {
restrict: 'E',
scope: {
count: '@',
sortKey: '@',
sort: '&'
},
templateUrl: 'app/directives/topDevices.tpl.html'
},
link: function(scope) {
scope.sort({
count: scope.count,
sortKey: scope.sortKey
});
}
});
如您所見,函數以不同的方式調用->傳遞一個對象,該對象的鍵是參數名稱及其對應的值
然后在使用指令的地方:
<top-devices sort="ctrl.sortByKey( count, sortKey)"></top-devices>
請注意,這不是調用函數,因為我們使用了'&'屬性定義
您甚至可以在指令的html模板中使用sort函數:
topDevices.tpl.html
<div ng-show="sort({count: count, sortKey: sortKey})">
<a href="#" ng-repeat...>{{something}}</a>
</div>
不是最聰明的例子,但您明白了
您也可以查看此相關答案
還有另一種傳遞函數的方式
<top-devices sort="ctrl.sortByKey"></top-devices>
然后,在“鏈接”功能中,您可以像這樣使用它
{
...
link: function(scope) {
var unwrapped = scope.sort();
unwrapped( scope.count, scope.sortKey);
}
}
小注釋-在您的示例中,您無法在使用它們的位置訪問“ this.count”和“ this.sortKey”:
1.它們尚未定義。 2.“ this”未引用作用域對象。
編輯實現目標的一種方法是使用過濾器:查看此小提琴以查看基本實現。 也許已經有一個內置的過濾器可以幫助您做到這一點。 過濾器可以組合:
<li ng-repeat="data in collection | filter1:arg | filter2:bar | filter1:foo></li>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.