我是angularjs的新手,我有数据绑定问题。
在每一条重复的行之后,我想展示一些互斥的选项。这些是使用背景图像的图像,当选择该选项时,我添加css类'选择'到包含图像的范围。
我在下面对其进行了简化,以显示选项A,B和C,并使当前选中的选项为粗体。通过单击A,B或C,您可以更改选项。
当模型改变时,内部ng-repeat部分不再被评估(似乎),而是作为"调试类别"显示,外部ng-repeat被重新评估,并且"调试类别"正确显示该类别已更改。
我明显遗漏了一些关于angularjs的事情;如何才能让内部ng-repeat重新评估,将正确的样式应用于A,B和C选项?
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var testApp = angular.module('testApp', []);
testApp.controller('NamesCtrl', function ($scope) {
$scope.categories = [ 'A', 'B', 'C' ];
$scope.names = [
{ name: 'John', category: 'C' },
{ name: 'Cindy', category: 'A' },
{ name: 'Patrick', category: 'B' }
];
$scope.changeCategory = function(name, category) {
name.category = category;
};
});
</script>
<body ng-app="testApp">
<h1>Names</h1>
<div ng-controller="NamesCtrl">
<ul>
<li ng-repeat="name in names">
<span>{{name.name}}</span>
<span ng-repeat="category in categories" ng-init="selected = (category == name.category)">
<span ng-style="{'true': {'font-weight': 'bold'}, false: {}}[selected]" ng-click="changeCategory(name, category)">{{category}}</span>
</span>
<em>(Debugging category: {{name.category}})</em>
</li>
</ul>
</div>
</body>
&#13;
答案 0 :(得分:1)
ng-init
表达式,您可以通过删除ng-init并直接使用表达式来解决此问题
<span ng-style="{'true': {'font-weight': 'bold'}}[category == name.category]"
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var testApp = angular.module('testApp', []);
testApp.controller('NamesCtrl', function ($scope) {
$scope.categories = [ 'A', 'B', 'C' ];
$scope.names = [
{ name: 'John', category: 'C' },
{ name: 'Cindy', category: 'A' },
{ name: 'Patrick', category: 'B' }
];
$scope.changeCategory = function(name, category) {
name.category = category;
};
});
</script>
<body ng-app="testApp">
<h1>Names</h1>
<div ng-controller="NamesCtrl">
<ul>
<li ng-repeat="name in names">
<span>{{name.name}}</span>
<span ng-repeat="category in categories" >
<span ng-style="{'true': {'font-weight': 'bold'}}[category == name.category]" ng-click="changeCategory(name, category)">{{category}}</span>
</span>
<em>(Debugging category: {{name.category}})</em>
</li>
</ul>
</div>
</body>