Javascript 如何在 ng-repeat 中正确执行函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26399783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to properly execute a function inside ng-repeat
提问by FrancescoMussi
SITUATION:
情况:
I am making an app in AngularJs that assign permissions. In order to do this i have three nested ng-repeat.
我正在 AngularJs 中制作一个分配权限的应用程序。为了做到这一点,我有三个嵌套的 ng-repeat。
First loop: display PERMISSION GROUP
第一个循环:显示权限组
Second loop: For each permission group display CATEGORIES. Inside this loop execute a function that will get all the SUB CATEGORIES for each category
第二个循环:为每个权限组显示 CATEGORIES。在此循环内执行一个函数,该函数将获取每个类别的所有 SUB CATEGORIES
Third loop: display SUB CATEGORIES
第三个循环:显示子类别
ISSUE:
问题:
The problem is in the execution of the function inside the second loop.
问题在于第二个循环中函数的执行。
ATTEMPT 1 - ng-init:
尝试 1 - ng-init:
<div class="row" ng-repeat="permission_group in list_permission_groups">
<div class="col-sm-3">
<h3>
{{permission_group.permission_group_name}}
</h3>
</div>
<div class="col-sm-9">
<ul>
<li ng-repeat="category in list_categories">
<span>
{{ category.name }}
</span>
<div class="checkbox">
<label>
<div ng-init="temp_result = get_Sub_Categories(category.category_id)">
<p ng-repeat="sub_category in temp_result">
{{ sub_category.name }}
</p>
</div>
</label>
</div>
</li>
</ul>
</div>
</div>
In the controller:
在控制器中:
$scope.get_Sub_Categories = function(category_id) {
$http({
url: base_url + 'main/json_get_list_sub_categories',
data: {
category_id: category_id
},
method: "POST"
}).success(function(data) {
return data;
});
}
Te behavior is quite strange. Porbably due to dirty checking the page is loaded 682 times. No result is displayed.
行为很奇怪。可能是由于脏检查页面加载了 682 次。不显示任何结果。
ATTEMPT 2 - ng-click: (only for debug)
尝试 2 - ng-click:(仅用于调试)
<div class="row" ng-repeat="permission_group in list_permission_groups">
<div class="col-sm-3">
<h3>
{{permission_group.permission_group_name}}
</h3>
</div>
<div class="col-sm-9">
<ul>
<li ng-repeat="category in list_categories">
<span>
{{ category.name }}
</span>
<div class="checkbox">
<label>
<button ng-click="get_Sub_Categories(category.category_id)">
GET SUB-CATEGORIES
</button>
{{ list_sub_categories }}
</label>
</div>
</li>
</ul>
</div>
</div>
In the controller:
在控制器中:
$scope.get_Sub_Categories = function(category_id) {
$http({
url: base_url + 'main/json_get_list_sub_categories',
data: {
category_id: category_id
},
method: "POST"
}).success(function(data) {
$scope.list_sub_categories = data;
});
}
This time the page is loaded only once. If I press the button the proper sub-categories are displayed BUT of course not only for the corresponding category but FOR ALL, because i am modifying the var in the global scope.
这次页面只加载一次。如果我按下按钮,则会显示正确的子类别,但当然不仅针对相应类别,而且针对所有类别,因为我正在修改全局范围内的 var。
THE AIM:
目的:
What I want to obtain is simply displaying all the proper sub-categories for each category. Without using a button, but simply see all the proper content as soon as the page load. But i don't understand how can this be done properly in AngularJs.
我想要获得的只是显示每个类别的所有正确子类别。无需使用按钮,只需在页面加载后立即查看所有正确内容。但我不明白如何在 AngularJs 中正确地做到这一点。
THE QUESTION:
问题:
How can i properly execute a function inside a ng-repeat that return and display different data for each loop?
如何在 ng-repeat 中正确执行一个函数,为每个循环返回并显示不同的数据?
EDIT- DUMP OF EXAMPLE OF SUB-CATEGORIES FOR ONE CATEGORY:
编辑- 一个类别的子类别示例的转储:
[{
"sub_category_id": "1",
"name": "SUB_CATEGORY_1",
"category_id_parent": "1",
"status": "VISIBLE"
}, {
"sub_category_id": "2",
"name": "SUB_CATEGORY_2",
"category_id_parent": "1",
"status": "VISIBLE"
}, {
"sub_category_id": "3",
"name": "SUB_CATEGORY_3",
"category_id_parent": "1",
"status": "VISIBLE"
}, {
"sub_category_id": "4",
"name": "SUB_CATEGORY_4",
"category_id_parent": "1",
"status": "VISIBLE"
}]
采纳答案by Amitesh
Calling a function inside ng-repeat is same as normal one. Since you need to display the sub categories at the time of page loading its better to get these data beforehand. Asynchronously loading sub categories will not fit into this scenario.
在 ng-repeat 中调用函数与正常调用相同。由于您需要在页面加载时显示子类别,因此最好事先获取这些数据。异步加载子类别不适合这种情况。
Here is a minimal snippet achieving this (JS Fiddle)
这是实现此目的的最小片段(JS Fiddle)
<div ng-app="app" ng-controller="ctrl">
<div ng-repeat="category in model.categories"> <span> Category: {{ category.name }} </span>
<p ng-repeat="subCategory in getSubCategories(category.Id)">{{ subCategory.name }}</p>
</div>
</div>
Controller
控制器
angular.module("app", [])
.controller('ctrl', ['$scope', function ($scope) {
$scope.model = {
categories: [{
"Id": 1,
name: '1'
}, {
"Id": 2,
name: '2'
}],
subCategories: [{
"parentId": 1,
name: 'a1'
}, {
"parentId": 1,
name: 'a2'
},
{
"parentId": 2,
name: 'a3'
}]
}
$scope.getSubCategories = function(parentId){
var result = [];
for(var i = 0 ; i < $scope.model.subCategories.length ; i++){
if(parentId === $scope.model.subCategories[i].parentId){
result.push($scope.model.subCategories[i]);
}
}
console.log(parentId)
return result;
}}])
回答by Sacky San
The subcategory example did not work for my case and it took my code into an infinte loop for some reason. may be because i was using an accordion.
子类别示例不适用于我的案例,并且出于某种原因将我的代码带入了无限循环。可能是因为我用的是手风琴。
I achieved this function call inside ng-repeat by using ng-init
我通过使用 ng-init 在 ng-repeat 中实现了这个函数调用
<td class="lectureClass" ng-repeat="s in sessions" ng-init='presenters=getPresenters(s.id)'>
{{s.name}}
<div class="presenterClass" ng-repeat="p in presenters">
{{p.name}}
</div>
</td>
The code on the controller side should look like below
控制器端的代码应如下所示
$scope.getPresenters = function(id) {
return SessionPresenters.get({id: id});
};
While the API factory is as follows:
API工厂如下:
angular.module('tryme3App').factory('SessionPresenters', function ($resource, DateUtils) {
return $resource('api/session.Presenters/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET', isArray: true
},
'update': { method:'PUT' }
});
});
回答by Quentin Leonetti
I think that the good solution here is to use Angular Directive.
我认为这里的好解决方案是使用 Angular Directive。
You can see an example of directive used in a ng-repeat here : Angular Directive Does Not Evaluate Inside ng-repeat
您可以在此处查看 ng-repeat 中使用的指令示例:Angular Directive does Not Evaluate Inside ng-repeat
For more information on directives, you can check the official documentation : https://docs.angularjs.org/guide/directive
有关指令的更多信息,您可以查看官方文档:https: //docs.angularjs.org/guide/directive
回答by JayMc
I would create a factory for category then move your get_sub_categories function into this new factory.
我会为类别创建一个工厂,然后将您的 get_sub_categories 函数移动到这个新工厂中。

