47

我想使用ng-model將複選框綁定到作用域。複選框的初始狀態與範圍模型相對應,但是當我選中/取消選中複選框時,模型不會更改。有些事情要注意的是,模板在運行時使用動態加載NG-包括複選框沒有綁定到angularjs中的作用域

app.controller "OrdersController", ($scope, $http, $location, $state, $stateParams, Order) -> 

    $scope.billing_is_shipping = false 
    $scope.bind_billing_to_shipping = -> 
    console.log $scope.billing_is_shipping 


<input type="checkbox" ng-model="billing_is_shipping"/> 

當我檢查箱子的控制檯日誌錯誤,當我取消選中該複選框,控制檯再次登錄假的。我也有一個訂單模型的範圍,如果我改變複選框的模型是order.billing_is_shipping,它工作正常

回答

127

我一直在努力解決這個問題。有效的是將輸入綁定到對象而不是原語。

<!-- Partial --> 
<input type="checkbox" ng-model="someObject.someProperty"> Check Me! 

// Controller 
$scope.someObject.someProperty = false 
+3

我有同樣的問題,並修復它。我想知道爲什麼原語不起作用(就像他們在[官方文檔](https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D)中所做的那樣)... – acdcjunior

+3

謝謝你這樣!不知道爲什麼這不適用於一個原始的,這可能只是一個在Angular中的錯誤? – jbisa

+1

謝謝...這完美的作品。 –

23

如果使用ng-include加載模板,您需要使用$parent來訪問定義在如果要通過單擊該複選框進行更新,請從ng-include開始父範圍。

<div ng-app ng-controller="Ctrl"> 
    <div ng-include src="'template.html'"></div> 
</div> 

<script type="text/ng-template" id="template.html"> 
    <input type="checkbox" ng-model="$parent.billing_is_shipping" ng-change="checked()"/> 
</script> 

function Ctrl($scope) { 
    $scope.billing_is_shipping = true; 

    $scope.checked = function(){ 
     console.log($scope.billing_is_shipping); 
    } 
} 

DEMO

+0

我更新了我的代碼,但它仍然沒有沒有使用$父工作在同一個模板 – chris

+0

另外,我還結合一些其他的特性,它適用於那些 – chris

+0

如果我初始化billing_is_shipping爲真,該複選框被初步遏制,所以它獲得了正確的價值,但僅僅因爲某種原因沒有在該複選框上綁定它 – chris

7

在我的指令(在鏈接功能)我創造了範圍可變成功這樣的:

link: function(scope, element, attrs) { 
      "use strict"; 

      scope.success = false; 

而且在範圍模板包括輸入標籤,如:

<input type="checkbox" ng-model="success"> 

這沒有奏效。

最後,我改變了我的範圍變量看起來像這樣:

link: function(scope, element, attrs) { 
      "use strict"; 

      scope.outcome = { 
       success : false 
      }; 

而且我輸入標籤看起來像這樣:

<input type="checkbox" ng-model="outcome.success"> 

現在按預期工作。我知道這個解釋,但忘記了,也許有人會填補我的。 :)

+0

註冊成功!我一直在努力解決相同的問題(我們都使用指令),現在已經有兩天了。這拯救了我的生命和我的最後期限。感謝您分享這一點! = o) –

8

擴展在Matt's answer,請參閱本Egghead.io視頻,解決這個問題很並且提供了一個解釋:Why binding properties directly to $scope can cause issues

見:https://groups.google.com/forum/#!topic/angular/7Nd_me5YrHU

通常這是因爲另一個指令在您的ng控制器 和您創建新範圍的輸入之間。當select將 寫出它的值時,它會將其寫入最近的作用域,所以它將 寫入此作用域而不是進一步 以外的父域。

最好的做法是不要直接在ng-model綁定變量的作用域 ,這也被稱爲總是包括 你ngmodel一個「點」。

+2

這個答案完全依賴於外部鏈接。如果他們變得無效,你的答案將變得毫無用處。所以請編輯它並至少添加一個可以在那裏找到的摘要。謝謝! –

+0

@FabioTurati編輯了我的回覆! – Rk220

+0

@FabioTurati如何有先見之明! YouTube視頻無法使用了! – Dinesh

相關問題