我有一个自定义指令,其中包含通过ng-repeat
动态创建的按钮列表,如下所示:
HTML
<div ng-controller="toggleButtonController" ng-init="init()" id="parent">
<div ng-repeat="btn in setting" style="display:inline">
<button class="btn" ng-bind="btn.name" ng-click="click(btn)" ng-class="getClass(btn, toggleButton.selected)"></button>
</div>
</div>
CONTROLLER
var app = angular.module('toggleButtonMod', [])
app.directive('toggleButton', function() {
return {
restrict: 'E',
scope: {
setting: '='
},
templateUrl: "app/Shared/togglebutton/toggleButtonView.html"
}
})
app.controller("toggleButtonController", function($scope) {
$scope.init = function() {
$scope.setupContent();
}
$scope.setupContent = function() {
$scope.toggleButton = {selected: null};
}
$scope.click = function(btn) {
$scope.toggleButton.selected = btn;
}
$scope.getClass = function(btn, toggleSelected){
if(btn === toggleSelected){
return 'btn-primary';
}else{
return 'btn-default';
}
}
})
此处的方案是创建服务或任何其他更好的实施,以更改ng-class
中特定按钮的ng-repeat
。
例如:
app.service('selectDefault', function(index) {
//set button #2 to have ng-class="btn-primary"
}
答案 0 :(得分:0)
我不确定这是否是您正在寻找的。但是,此代码段将显示如何使用服务在ng-repeat
中动态添加课程。希望它有所帮助!
答案 1 :(得分:0)
只需将ng-class
更改为:
ng-class="{'btn-primary':(btn === toggleSelected), 'btn-default':(btn != toggleSelected)}"
假设变量toggleSelected
设置在代码中的某个位置,虽然我没有看到它在上面的示例中设置。