如果我有一个数据库对象,它通过我的Angular App中的JSON加载,我会使用这样的结构:
数据
{
"colours": ["red","yellow","pink","green","purple","orange","blue"]
}
控制器
angular.module('MyApp').controller('Page_controller',function($scope,$http) {
$scope.addColour = function(e) {
$scope.data.colours.push('')
};
$scope.removeColour = function(e) {
var colour_index = $scope.data.colours.indexOf(the_colour_name);
$scope.data.colours.splice(colour_index,1);
}
$http.json("/database/query.json").success(function(data) {
$scope.data = data;
})
})
/views/display.html
<div>
<ul>
<ng-include="'/templates/colour.html'" ng-repeat="colour in data.colours"></ng-include>
<li><a href="" ng-click="addColour()" required>Add a colour</a></li>
</ul>
<div id="correct">CORRECT</div>
</div>
/templates/colour.html
<li><input type="text" ng-model="colour" placeholder="Name of colour"></input> <a href="" ng-click="removeColour(some_way_to_refer_to_this_colour)">X</a></li>
现在我可以为列表添加颜色并将其删除。 (是的,删除它们有点不清楚,我认为你们都可以看到我想要做的事情!)
我的问题是:如果颜色是最初加载的颜色,我怎样才能显示#correct
div?
答案 0 :(得分:1)
将colors数组复制到其他范围变量,例如$scope.originalColours
。
在HTML中添加ng-show:
<div ng-show="showCorrect">CORRECT</div>
向您的控制器添加一块手表:
$watch('data.colours', function() {
if($scope.data.colours.length === $scope.originalColours.length) {
// Compare arrays $scope.data.colours and $scope.originalColours.
// If the two arrays are the same, set $scope.showCorrect
// to true and return.
}
$scope.showCorrect= false;
}, true);