2015-06-08 94 views
1

嗨,我的代碼工作正常,當點擊ng點擊切換複選框,如果複選框是未選中,它可以檢查時通過$ scope。$ watch()輸入輸入標籤中的數字。但是當我輸入數字後點擊'toggleCheckBox()'到取消勾選'Shopping'標籤的複選框,ng-class不起作用。 $ scope。$ watch()顯示「Hello World!」但不是初始化$ scope.checkShopping = true;可能是什麼問題呢? 這是代碼。非常感謝!

$scope.toggleCheckbox = function (mainModel, subModel) { 
 

 
     var index = $scope[mainModel].indexOf(subModel); 
 
     if (index >= 0) { 
 
      $scope[mainModel].splice(index, 1); 
 
     } else { 
 
      $scope[mainModel].push(subModel); 
 
     } 
 
    }; 
 

 

 
$scope.$watch('Shopping',function(){ 
 
    if($scope.Shopping > 0){ 
 
    $scope.checkShopping = true; //this code is not working on 2nd input. The ng-class is not setting to 'TRUE' 
 
    console.log("Hello world!"); 
 
    } 
 
});
\t .checkListHolder { 
 
\t \t width: 100%; 
 
\t \t display: block; 
 
\t \t overflow: hidden; 
 
\t } 
 

 
\t .checkListHolder > li { 
 
\t \t display: inline-block; 
 
\t \t width: 100%; 
 
\t \t float: left; 
 
\t \t overflow: hidden; 
 
\t \t padding: 5px 0; 
 
\t } 
 

 
\t .checkedListItem .checkboxList { 
 
\t \t background-image: url(../images/form-icons/checkbox-on.png); 
 
\t } 
 

 
\t .checkboxList { 
 
\t \t width: 20px; 
 
\t \t height: 20px; 
 
\t \t background-repeat: no-repeat; 
 
\t \t background-position: center; 
 
\t \t background-image: url(../images/form-icons/checkbox-off.png); 
 
\t \t margin: 0 10px 0 0; 
 
\t \t cursor: pointer; 
 
\t } 
 

 
\t .checkboxLabel { 
 
\t \t width: auto; 
 
\t \t float: left; 
 
\t \t overflow: hidden; 
 
\t \t color: #FFF; 
 
\t \t font-size: 14px; 
 
\t \t font-family: "Open Sans", sans-serif!important; 
 
\t }
<li ng-class="{checkedListItem : checkShopping == true}"> 
 
    <div class="checkboxList" ng-click="toggleCheckbox('PleasureVacationList','Shopping')"> </div> 
 
    <div class="checkboxLabel">Shopping</div> 
 
</li> 
 
<li> 
 
    <input type="number" ng-model="Shopping"> 
 
</li>

可以採取什麼問題嗎?感謝您的幫助

回答

1

這是直接在範圍上分配變量的問題之一。因爲你改變了指針,而不僅僅是變量的值,所以角度的摘要週期不會改變。有多種修正爲:

/* 1: apply the function in the digest cycle */ 
$scope.$apply(function() { 
    $scope.checkShopping = true; 
}); 

/* 2: apply to the whole digest cycle */ 
$scope.checkShopping = true; 
$scope.$apply(); 

/* 3: use an object with initialization */ 
$scope.shopping = { 
    checkShopping: false 
} 

// then the following will be picked up by angular's digest cycle: 
$scope.shopping.checkShopping = true; 

Here's爲什麼這種情況正在發生

+0

怎麼會角不會注意到這是一個很好的解釋,雖然它在它的$範圍,並且所有? –

+0

它仍然沒有工作devqon ...輸入數字後,切換到取消選中複選框。我輸入數字到輸入標籤,但$ scope.checkShopping = true;不起作用 –

+0

請包含jsfiddle來複制 – devqon

相關問題