2014-12-29 32 views
5

所以我做了一些實驗,在同一個$範圍內創建一個在2個不同選擇框上的ng-change行爲。一個是在ng-include指令中,另一個是在ng-include指令之外,有趣的部分是當我實現數據綁定的時候它變成了好的,但是當我試圖看看我的控制檯選項卡時它會以不同的方式返回

的NG-包括指令外的一個是好的,而一個內的NG-包括指令總是返回值「a」或靜態值

這是的index.html樣機

<select ng-model="list" ng-change="changeOutsideTemplate()"> 
    <option value="a">A</option> 
    <option value="b">B</option> 
    </select> 

    {{list}} 

    <div ng-include="test"></div> //this scope caries test.html 

這是test.html樣機

<select ng-model="list" ng-change="changeInsideTemplate()"> 
    <option value="a">A</option> 
    <option value="b">B</option> 
</select> 

{{list}} 

這是控制器

var app = angular.module('myApp', []); 

app.controller('MainCtrl', function($scope) { 
    $scope.name = 'World'; 
    $scope.test = "test.html"; 
    $scope.list = "a"; 

    $scope.changeInsideTemplate = function() { 
    console.log($scope.list); //always returns 'a' 
    } 

    $scope.changeOutsideTemplate = function() { 
    console.log($scope.list); //this is the correct way 
    } 

}); 

,這是工作example

爲什麼你認爲這個問題的原因是什麼?任何人都在關心精心製作?

回答

7

ng-include指令創建一個新的子範圍。 這裏是DOC

當你在ng-include HTML模式爲<select ng-model="list" ng-change="changeInsideTemplate()">然後角將檢查其子範圍模型list,則角將實現沒有modelng-include子範圍中調用list。那麼角將在子範圍內創建一個名爲list的新子範圍模型。

如果妳不喜歡

<select ng-model="$parent.list" ng-change="changeInsideTemplate()"> 

然後將角在父母範圍檢查模式list。在ng-include的範圍內包含我們關心的$scope.list

這裏是工作Plunker


或者你可以使用如下的@dfsq在意見建議。

控制器

app.controller('MainCtrl', function($scope) { 
    $scope.name = 'World'; 
    $scope.test = "test.html"; 
    $scope.list = {value: 'a'}; 

    $scope.changeInsideTemplate = function() { 
    console.log($scope.list.value); //always returns 'a' 
    } 

    $scope.changeOutsideTemplate = function() { 
    console.log($scope.list.value); //this is the correct way 
    } 
}); 

的index.html

<select ng-model="list.value" ng-change="changeOutsideTemplate()"> 

測試。HTML

<select ng-model="list.value" ng-change="changeInsideTemplate()"> 

test.html角度將檢查list.value然後角就知道value是一個對象的屬性,也沒有叫list與子範圍對象。那麼角將在父範圍內搜索對象(list),就像它將搜索整個層次結構一樣。

這裏是Plunker


,如果你有ng-includeng-include然後第二ng-include創建第一ng-include

然後小孩範圍在test.html

<div ng-include="$parent.include"></div> // because `$scope.include` in parent scope 

include.html

<select ng-model="$parent.$parent.list" ng-change="otherChanging()"> // because `$scope.list` is in parent scope of parent scope (second upper parent scope). 

這裏是使用$ parent的Plunker

這裏是使用Object的Plunker

使用對象更合適。

+3

這是正確的。或者更好的解決方法是使用'$ scope.list = {value:'a'}'better和'ng-model =「list.value」'。 – dfsq

+0

上帝現在你提到它我可以看到有關文檔的指令信息..哇有趣,所以這就是爲什麼它不工作就像它應該工作..感謝您的解釋,我現在明白了! –

+0

順便說一句,如果案件是這樣的? http://plnkr.co/edit/KjHSgyeLQ2CYgnsFrO3J?p=preview –

相關問題