2017-04-27 62 views
0

我有一個單擊切換按鈕,當點擊活動時它會改變顏色。但現在我堅持如何在控制器中獲得按鈕的值(激活或不激活)。我應該如何處理這個問題?檢查按鈕是否處於活動狀態或不在控制器中

這裏的錯誤代碼:

TypeError: Cannot read property 'clicked' of undefined 

這裏的html代碼:

<button class="button button-clear icon ion-star button-energized" ng-model="singleTog" ng-click="toggleButton(item.name)" ng-class="singleTog.clicked?'button-energized':'button-dark'" ></button> 

和這裏的controller.js代碼:

$scope.toggleButton = function(candidateName) 
{ 
    $scope.singleTog.clicked=!$scope.singleTog.clicked 
    if($scope.singleTog.clicked==true) 
    { 
    if(favoriteList.indexOf(candidateName) == -1) //does not exist in array 
    { 
     $scope.numbers.push(candidateName); 
    } 
    } 
    else 
    { 
    if(favoriteList.indexOf(candidateName) != -1) //exists in array 
    { 
     var index = $scope.favoriteList.indexOf(candidateName); 
     $scope.favoriteList.splice(index, 1); 
    } 
    } 

    alert('favorites = ' + favoriteList); 
} 
+1

嘗試定義默認狀態'$範圍.singleTog = {}',在'$ scope.toggleButton'之前 – Leguest

+0

你在哪裏初始化$ scope.singleTog? –

回答

0

定義一個emty對象$scope.singleTog = {}

試試這個

$scope.singleTog = {} 
$scope.toggleButton = function(candidateName) 
{ 
    $scope.singleTog.clicked=!$scope.singleTog.clicked 
    if($scope.singleTog.clicked==true) 
    { 
    if(favoriteList.indexOf(candidateName) == -1) //does not exist in array 
    { 
     $scope.numbers.push(candidateName); 
    } 
    } 
    else 
    { 
    if(favoriteList.indexOf(candidateName) != -1) //exists in array 
    { 
     var index = $scope.favoriteList.indexOf(candidateName); 
     $scope.favoriteList.splice(index, 1); 
    } 
    } 

    alert('favorites = ' + favoriteList); 
} 
0

如果你只是想更改按鈕的顏色,當它有效或無效,您可以使用該納克級:

ng-class="$variableToEvaluate ? 'class-if-true' : 'class-if-false'" 
相關問題