Angularjs:如何访问ng-repeat中的特定项目

时间:2018-04-04 02:29:01

标签: javascript angularjs angularjs-ng-repeat

我有一个自定义指令,其中包含通过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"
}

2 个答案:

答案 0 :(得分:0)

我不确定这是否是您正在寻找的。但是,此代码段将显示如何使用服务在ng-repeat中动态添加课程。希望它有所帮助!

<强> https://jsfiddle.net/cgdmqt8o/

答案 1 :(得分:0)

只需将ng-class更改为:

即可
ng-class="{'btn-primary':(btn === toggleSelected), 'btn-default':(btn != toggleSelected)}"

假设变量toggleSelected设置在代码中的某个位置,虽然我没有看到它在上面的示例中设置。