【发布时间】:2017-02-11 17:25:02
【问题描述】:
我有一个带有这样输入框的标签:
<label class="item item-input">
<input type="text" data-ng-model="description"
placeholder="Add a Description!">
</label>
如你所见,这个输入框被绑定到范围“描述”
在我的控制器中,我有一些类似的东西:
$scope.description = "";
$scope.submit = function() {
console.log($scope.description);
};
在我的 HTML 中,我也有这一行:
<div ng-show="description.length <= maxChars">{{description}}</div>
当用户在输入框内输入后点击提交按钮时,提交函数被调用。说明正确显示。当用户在输入框中输入内容时,描述会在 HTML 中更新,但不会在控制器中更新。
我感觉这与将描述设置为空字符串有关,但就 HTML 而言,它显然正在更新。但无论如何它都会保留 console.logging 和空字符串。
为了让它工作,我必须将描述直接传递到提交函数中(并相应地更新函数):
<button class="button button-positive" data-ng-click="submit(description)">Submit</button>
这是完全没有必要的,因为 Angular 应该自动进行双向数据绑定,但事实并非如此。
有人有什么想法吗?
任何帮助将不胜感激。
编辑:
由于受欢迎的需求,这里是完整的 HTML。
<ion-view title="Moments" id="page2">
<ion-content padding="true" class="has-header">
<img src="{{picture}}" height="300px" width="100%"> </img>
<div class="row">
<div ng-show="description.length > maxChars" style= "color: red">{{description}}</div>
<div ng-show="description.length <= maxChars">{{description}}</div>
</div>
<div class="row" ng-if="description">
<div ng-show="description.length > maxChars" style= "color: red">{{description.length}} / {{maxChars}}</div>
<div ng-show="description.length <= maxChars" style= "color: green">{{description.length}} / {{maxChars}}</div>
</div>
<div class="row">
<div class="col">
<label class="item item-input">
<input type="text" data-ng-model="description" placeholder="Add a Description!">
</label>
</div>
<button style="margin-right: 5px" class="col col-10 button button-positive" data-ng-click="checkDescription(description)">OK</button>
</div>
<div class="row">
<div class="col"><ion-checkbox data-ng-change="changeLocation()" data-ng-model="location">Show Location</ion-checkbox></div>
</div>
<div class="row">
<div class="button-bar">
<button class="button button-assertive" data-ng-click="cancel()">Cancel</button>
<button class="button button-positive" data-ng-click="submit(description)">Submit</button>
</div>
</div>
</ion-content>
</ion-view>
我也知道在这个问题中,提交函数不带参数。这就是我想要的样子。目前我的提交按钮采用一个参数(描述)。这不应该是必要的。我对函数“checkDescription”也有同样的问题。该函数也应该没有参数,但我不得不将描述直接传递给函数。我不想做的事情。
【问题讨论】:
-
它应该会正确更新。也不需要看。但是你能完整地发布你的代码吗?或者小提琴
-
顺便说一句,您在 html 中使用 'submit(description)' 但声明 'submit = function()' ...
-
是否有
ng-if或ng-repeat或其他指令在输入元素和控制器之间创建范围?在 ng-models 中不使用点.时可能会导致问题。有关详细信息,请参阅AngularJS Wiki -- The Nuances of Scope Prototypal Inheritance。
标签: angularjs data-binding angularjs-scope