我遇到的问题是从我的视图输入的文本字段没有绑定到控制器。
这里是视图片段:
<md-dialog-content ng-if="mode=='addSentence'" class="sticky-container">
<md-input-container>
<label for="sentence-text">Enter the sentence to be corrected</label>
<input ng-model="theSentence" name="sentence-text"/>
</md-input-container>
<span flex>{{ error }}</span>
<md-button class="primary" style="float:right;" aria-label="Save" ng-click="saveNewSentence()">Save</md-button>
</md-dialog-content>
这里是应该处理输入的控制器功能:
function ViewSentenceController($scope, $rootScope, $mdDialog) {
$scope.mode = mode;
$scope.user = user;
$scope.theSentence = null;
$scope.saveNewSentence = function() {
console.log($scope.theSentence);
}
$scope.cancel = function() { $mdDialog.hide(); }
}
当调用saveNewSentence()
时,它会将null
记录到控制台,即使我在文本字段中有输入。
我确定我错过了一些东西,我无法看到它,但我在这个简单的问题上花了太多时间,所以提前感谢您的帮助!
答案 0 :(得分:2)
您的对话框具有自己的$ scope。所以:
<input ng-model="$parent.theSentence" name="sentence-text"/>
</md-input-container>
答案 1 :(得分:1)
请设置&#39; preserveScope:true&#39;在您的md对话框选项或..我不确定,但尝试将您的ng模型更改为ex:&#34; dialogObj.theSentence&#34;并阅读此console.log($scope.dialogObj.theSentence);
答案 2 :(得分:1)
如果您可以分享完整代码块的js-fiddle,我可以帮助您更好。但下面是一个示例,其中我创建了2个最初设置为null的输入字段,然后我不断更新我的ng模型。
<body data-ng-app="formApp">
<div data-ng-controller="FormCtrl">
<p>
Name of Topic: <input type="text" data-ng-model="formData.title" placeholder="enter a title" />
</p>
Subscribers:
<button data-ng-click="addSubscriber()">Add subscriber</button>
<table>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
<tr data-ng-repeat="subscriber in formData.subscribers">
<td><input type="text" data-ng-model="subscriber.name" placeholder="enter name" /></td>
<td><input type="text" data-ng-model="subscriber.email" placeholder="enter email" /></td>
</tr>
</table>
<hr style="margin:1em 0;" />
<p>
<em>Debug info</em>: {{ formData }}
</p>
</div>
和JS如下所示。
(function() {
var formApp = angular.module("formApp", []);
formApp.controller("FormCtrl", function ($scope, $timeout) {
$scope.formData = {};
$scope.formData.subscribers = [
{ name: null, email: null }
];
$scope.addSubscriber = function() {
$scope.formData.subscribers.push({ name: null, email: null });
};
});
})();
如果有帮助,请告诉我。
答案 3 :(得分:0)
我在某种程度上通过传递“绑定”来解决了这个问题。数据作为函数的参数,而不是让Angular绑定文本字段中的数据,我调用了saveNewSentence()
theSentence
传递给它的saveNewSentence(theSentence)
参数,例如:where
。有效。对我来说似乎是一个便宜的伎俩,但是:
如果它很愚蠢并且有效,那么它就是愚蠢的
希望这有助于其他一些困惑的灵魂出现类似的问题。