在AngularJS中执行ng-repeat内的函数 [英] Execute a function inside ng-repeat in AngularJS
问题描述
我想在ng-repeat中执行一个函数来检索要显示的其他数据。
I would like to execute a function inside a ng-repeat to retrieve some other data to show.
例如我有一个公寓列表。我使用 ng:repeat
显示此列表,而不是我希望向所有者显示的每个公寓,而不是 u.Apartments
。所以我的 getInq
函数调用服务来获取指定公寓的所有者。这对我来说似乎是逻辑,但它不起作用。
它返回 10 $ digest()迭代次数。正在中止!
错误。
For example I've a list of Apartments. I show this list using ng:repeat
, than for each Apartment I would like to show the Owner, that is not the u.Apartments
. So my getInq
function make a call to a service to get the owner of a specified apartment. It seems to be logic for me, but it doesn't work.
It returns the "10 $digest() iterations reached. Aborting!"
error.
我有这段代码:
<div ng:repeat="u in units">
<div ng:repeat="a in u.Apartments">
<div class="targhetta" style="margin-top:10px">{{a.Name}}</div>
<br />{{getInq(a.ApartmentId)}}
<table>
<tr ng:repeat="cs in a.CS">
<td>{{cs.Position}}</td>
<td>{{cs.Code}}</td>
</tr>
</table>
</div>
</div>
在控制器中:
$scope.getInq = function (idApp) {
$http.get('http://localhost:8081/api/registry/GetLastInq?processdata=' + (new Date()).getTime() + '&appartamentoId=' + idApp, { headers: headers })
.success(function (data2) {
$scope.nomeInquilinoVw = data2.Name;
$scope.cognomeInquilinoVw = data2.Surname;
$scope.nomeCognome = $scope.nomeInquilinoVw + " " + $scope.cognomeInquilinoVw;
})
.error(function () {
$scope.success = false;
$scope.error = "There was an error!";
});
return $scope.nomeCognome;
}
有任何建议吗?
推荐答案
您应该在ng-repeat的任何数据中创建自定义指令传递,并执行您想要的任何操作。该指令将在每个ng-repeat循环上触发其链接函数
You should create a custom directive pass in any data you want from the ng-repeat and do any action you want. The directive will fire its link function on every ng-repeat loop
var app = angular.module('myApp', [])
.controller('myCtrl', function($scope){
$scope.data = ['a', 'b', 'c'];
})
.directive('myDirective', function(){
return {
restrict: "A",
template: '<div>{{ myDirective }}</div>', // where myDirective binds to scope.myDirective
scope: {
myDirective: '='
},
link: function(scope, element, attrs) {
console.log('Do action with data', scope.myDirective);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<ul>
<li ng-repeat="item in data" my-directive="item">{{ item }}</li>
</ul>
</div>
</div>
检查控制台是否有动作
这篇关于在AngularJS中执行ng-repeat内的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!