1
我嘗試顯示不同問題的列表。每個問題都有自己的表單輸入。所以我寫了一個指令來設置這些表單輸入。但在input
標記中設置ngModel
將不會更新隔離範圍。在具有隔離範圍的指令中輸入表單:如何將ngModel設置爲正確的範圍?
我現在已經嘗試:
<body ng-app="stepModule" ng-controller="ChallengeCtrl">
<div question step="step"></div>
</body>
而且JS:
angular.module('stepModule', [])
.directive('question', function() {
return {
restrict: 'A',
replace: true,
scope: {
step: '='
},
template: "<form ng-submit=\"submit()\">\n
Step = {{step}}\n
<label for=\"question\">Question</label>\n
<input ngModel=\"step.question\" ng-required=\"true\" name=\"question\" />\n
<label for=\"answer\">Answer</label>\n
<input ngModel=\"step.answer\" ng-required=\"true\" name=\"answer\" />\n
<input type=\"submit\" value=\"Save (extract out, should save automatically)\" />\n
</form>",
controller: [
"$scope", "$element", "$attrs", function($scope, $element, $attrs) {
$scope.submit = function() {
console.log($scope.step.question);
console.log($scope.step.answer);
};
}
]
};
});
這裏console.log
將輸出$scope.step
而不是新的價值的原始內容。 Here a Plunker顯示該行爲。
有沒有辦法讓ngModel
使用指令範圍?還是我只是失去了一些東西/濫用AngularJS(這不會讓我感到吃驚的至少...)
當然!該死的轉變。謝謝,這是有效的。 –
@andreas。爲什麼你不使用單引號作爲模板的開始和模板。那麼你不必逃避雙引號。 – zszep