2014-11-05 2 views
0

4 개의 버튼을 생성하기 위해 ngRepeat를 사용하고 있습니다. 단추 중 하나를 클릭 할 때마다 색을 변경하고 함수를 실행하고 싶습니다 (지금은 단순성을 위해 console.log를 사용하고 있습니다). 다른 버튼을 클릭하면 이전 버튼을 원래 색상으로 되 돌리는 동안 색상을 변경하고 싶습니다.ngRepeat 생성 버튼 목록에서 단일 버튼 색상 변경

두 가지 문제가 있습니다. 첫 번째는 ng-click을 통해 두 명령을 받아 들일 수없는 것입니다 (첫 번째는 console.log 기능이고 두 번째는 버튼 색을 변경하는 명령 임) . 다른 문제는 console.log 기능을 꺼내면 하나를 클릭 할 때 모든 버튼이 변경된다는 것입니다.

아이디어가 있으십니까? 다음은 기수입니다 : http://plnkr.co/edit/x1yLEGNOcBNfVw2BhbWA. console.log는 작동하지만 버튼 변경은 작동하지 않습니다. 이 ng-click에 대해 잘못된 것이 있습니까?

<span class="btn cal-btn btn-default" ng-class="{'activeButton':selectedButt === 'me'}" ng-click="log(element);selectedButt = 'me'" data-ng-repeat="element in array">{{element}}</span> 
+0

Oh god ... ng-click은 plunkr에서 작동하며 console.log와 색상 변경을 실행합니다. 이제 왜 작동하지 않는지 알아야합니다. 그러나 다른 단추를 클릭 할 때 변경된 단추를 원래 색으로 변경하는 방법을 찾는 데 도움이 될 수 있습니다. – nairys

답변

3

당신은이 논리 처리 컨트롤러에서 간단한 함수 만들 수 있습니다 : 현재 버튼이 활성화 된 경우

$scope.selectButton = function(index) { 
    $scope.activeBtn = index; 
} 

을, 당신은 단순히 템플릿에서 확인할 수 있습니다

<span class="btn cal-btn btn-default" ng-class="{true:'activeButton'}[activeBtn == $index]" ng-click="selectButton($index);" ng-repeat="element in array">{{element}}</span> 

나는 또한 당신의 것을 바 꾸었습니다 plunkr

1

당신은 당신의 원소 목록 f 문자열 배열을 먼저 객체 배열에 매핑하십시오. 당신의 HTML에,

$scope.log = function(element) { 
    console.log(element.name); 

    angular.forEach($scope.array, function(elem) { 
    elem.checked = false; 
    }); 

    element.checked = !element.checked; 
} 

다음 :

$scope.array = [ 
    {"name":"first", "checked":false}, 
    {"name":"second", "checked":false}, 
    {"name":"third", "checked":false}, 
    {"name":"fourth", "checked":false} 
]; 

그리고 로그 기능을 변경해야

<button class="btn cal-btn" 
    ng-repeat="element in array" 
    ng-click="log(element)" 
    ng-class="{activeButton: element.checked, 'btn-default': !element.checked}" 
    >{{element.name}}</button> 

업데이트 된 plunker here를 참조하십시오.