我还是AngularJS的新手。在线学习了多个教程之后,我在ng-if
指令中使用了一个javascript函数来验证一个组名是否已存在于数组中。如果是,则跳过ng-if
块以进行下一次ng-repeat
次迭代。如果没有,请将组名添加到数组并创建ng-if
块。这是HTML代码在partial中的样子:
HTML
<span ng-if="checkGroups(service.group.name)">
<!--Make nested list-->
</span>
这是javascript的简化版本:
JAVASCRIPT
(function () {
'use strict';
MainApp.controller('MainController', [
'$scope',
'Filters',
'helper',
'$timeout',
'$filter',function(
$scope,
Filters,
helper,
$timeout,
$filter) {
var MainCtrl = this;
//Function to check group array variable
$scope.usedGroups = [];
$scope.checkGroups = function(name) {
var isValid = true;
for(var i = 0; i < $scope.usedGroups.length; i++) {
if($scope.usedGroups[i] == name){
isValid = false;
break;
}
}
if(isValid == true){
$scope.usedGroups.push(name);
console.log($scope.usedGroups);
}
return isValid;
}
}
]);
})();
我使用console.log()
来返回值,我确实得到一个包含内部组名的数组,以及返回的true或false值。问题是ng-if
函数似乎只返回false。如果我将指令函数切换为“checkGroups(service.group.name)== false”,它将继续创建HTML块。我有什么想法可以解决这个问题?
答案 0 :(得分:0)
我已经用控制器中的一个简单对象数组替换了您的服务,因为我不想创建它。但下面应该做的伎俩,注意我翻了逻辑。这将仅显示一次,如果对象已存在则不会显示/插入。
var app = angular.module("MyApp", []);
var MyController = function($scope) {
// Somewhere in your service
$scope.service = {
group: [{
name: "Foo"
}
]
}
//Function to check group array variable
$scope.usedGroups = [];
$scope.checkGroups = function(name) {
for (var i = 0; i < $scope.usedGroups.length; i++) {
if ($scope.usedGroups[i] == name) {
console.log(name + " exists already!", $scope.usedGroups);
return true;
}
}
$scope.usedGroups.push(name);
console.log(name + " doesn't exist!\n", $scope.usedGroups);
return false;
}
}
app.controller(MyController, "[$scope, MyController]");
&#13;
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="MyApp">
<div ng-controller="MyController">
<div ng-repeat="item in service.group"> <!-- This is ran three times, just like calling it with three different names, but I put it in the controller to make it accessible -->
<span ng-if="checkGroups(item.name)">
{{ item.name }}
<!--Make nested list-->
</span>
</div>
</div>
</body>
</html>
&#13;