2013-06-30 21 views
5

我有簡單的控制器代碼:爲什麼範圍值不能通過使用「切換」技術從HTML更改?

JS

$scope.showErrorAlert = false; 


$scope.switchBool = function(value) { 
    value = !value; 
}; 

HTML

<div class="alert alert-error" ng-show="showErrorAlert"> 
       <button type="button" class="close" data-ng-click="switchBool(showErrorAlert)" >×</button> 
       <strong>Error!</strong> {{errorTextAlert}} 
      </div> 

從代碼片段你可以看到,我試圖改變$scope.showErrorAlert值。

但是它不起作用,value更改但不是showErrorAlert

有人可以告訴我爲什麼以及如何使它工作嗎?

謝謝

+0

+1你的問題很好:) –

回答

5

其他人已經給你一個正確的答案,爲什麼傳遞的變量沒有在範圍上改變。但是,如果你真正的用例僅僅是切換布爾值之外還有實現這個目的的至少兩個其他更簡單的方法:

一)切換直接ngClick表達式中的變量:

<button type="button" ng-click="showErrorAlert = !showErrorAlert">×</button> 

b )通過傳遞變量名到一個通用的「開關」功能切換變量:

<button type="button" ng-click="switchBool('showErrorAlert')">×</button> 
$scope.switchBool = function(var){ 
    $scope[var] = !$scope[var]; 
}; 
+0

好例子(b)'$ scope [var] =!$ scope [var];',謝謝 –

2
$scope.showErrorAlert = false; 


$scope.switchBool = function(value) { 
    value = !value; 
}; 

當值傳遞給switchBool,它是按值傳遞,而不是引用。所以該值只在該函數內發生變化。

你可以嘗試通過它的變種名稱,如$scope.showErrorAlert然後做內switchBool是這樣的:

eval(value + " = !" + value); 
在行動

http://jsfiddle.net/Npp2N/1/

$scope.showErrorAlert = false; 
$scope.switchBool = function(value) { 
    eval(value + " = !" + value); 
}; 

console.log($scope.showErrorAlert); // false 
$scope.switchBool("$scope.showErrorAlert"); 
console.log($scope.showErrorAlert); // true 
6

JS按值傳遞的參數。傳遞引用的簡單替代方法是傳遞一個對象(而不是屬性本身)。

I.e.

$scope.showErrorAlert = { value: false }; 

$scope.switchBool = function(obj) { 
    obj.value = !obj.value; 
}; 

或者你可能重構switchBool代碼在$範圍本身進行操作。你需要硬編碼或抽象「showErrorAlert」,然後,艱難。取決於你的要求。

+2

沒有必要宣佈新的對象語法只使用$ scope.sh owErrorAlert = {value:false} –