爲什麼默認值完全顯示?我認爲它只是應該將一個元素綁定到一個範圍屬性。我沒有意識到它與預填充有什麼關係。爲什麼第一個文本框預先填充在這裏,但不是第二個?ng-model爲什麼有時會預先填充,有時不會?
JS ...
angular.module('epfApp', [])
.controller('MainCtrl', function ($scope, $window) {
$scope.questions = {
'1': {
'title': 'Why does a default value work here?',
'type': 'text',
'default': 'first question'
}
};
$scope.myChange = function() {
console.log("a change just occurred");
};
});
HTML ...
<div ng-controller="MainCtrl">
<label ng-repeat="question in questions">
{{question.title}}
<input type="text" ng-model="question.default" ng-change="change()" />
<br />
</label>
<br />
<label>
Why does a default value NOT work here:
<input type="text" ng-model="banana" ng-change="change()" />
<br />
</label>
</div>
編輯:我很欣賞的答案。我認爲這是把我拋棄的轉發器。對於每個元素,ng模型值不需要是唯一的嗎?我知道這是錯誤的,但我覺得我需要'ng-model ='question.default {{$ index}}''或其他東西來強制賦予ng-model的東西是唯一的。
編輯2: 我認爲指令的工作是修改DOM。查看源代碼後,我看到dom已經被添加了各種類和註釋,但ng-model的值仍然是相同的(question.default),也就是說,它們仍然依賴於ng-repeat指令使他們獨一無二。那麼,ng-repeat似乎是一個例外,因爲ng-model的唯一(索引)名稱是隱含的,但從技術上來說並沒有實際反映在DOM中?
更新http://jsfiddle.net/ubwa4jgs/
<div ng-controller="MainCtrl" class="ng-scope">
<!-- ngRepeat: question in questions --><label ng-repeat="question in questions" class="ng-scope ng-binding">Why does a default value work here?
<input type="text" ng-model="question.default" ng-change="myChange()" class="ng-pristine ng-valid">
<br>
</label><!-- end ngRepeat: question in questions --><label ng-repeat="question in questions" class="ng-scope ng-binding">Why does a default value work here too?
<input type="text" ng-model="question.default" ng-change="myChange()" class="ng-pristine ng-valid">
<br>
</label><!-- end ngRepeat: question in questions -->
<br>
<label>Why does a default value NOT work here:
<input type="text" ng-model="banana" ng-change="myChange()" class="ng-pristine ng-valid">
<br>
</label>
</div>
感謝您的回覆。我無法理解的是,使用ng-model,你可以明顯地將它賦予一個非唯一值。例如,我習慣於看到ng-model =「user.name」。然後在控制器中,像「$ scope.user = {name:'Buddy'};」但是,上面的方式等價於將自身賦值給ng-model,例如, 「ng-model ='Buddy'」,這似乎很奇怪,因爲它們可能是Buddy的多個用戶名,這意味着潛在的冗餘ng模型?對不起,已經很晚了。希望明天我會看到我的方式錯誤。再次感謝。 –
而不是從頭開始我真的只是試圖理解ng模型的正確分配,也許一個更簡單的方法問,第一個文本框是什麼等同於香蕉?是不是必須將ng-model分配給唯一的變量名稱? –
@ user1893249 ng-model只需要一個對象屬性。在我的回答中,輸入模型是** questions [$ index] .value **,在您的問題中它是question.default,因此您在輸入中看到的值是'第一個問題'。我也剛剛意識到,question.default實際上是確定的,您不需要像我所示的那樣使用$ index,因爲repeat中的每個問題都是一個單獨的對象。你需要分配一個**唯一的對象屬性**。 –