[英]Getting user input text with $watch in AngularJS not working on ng-if
我有一个使用AngularJS,Monaca和OnsenUI构建的跨平台应用程序。
我有一个登录视图,该视图通过查询SQLite数据库检查用户是否已登录。 根据数据库中是否有数据,我向用户显示欢迎消息,或者显示登录文本字段。
我有一个查询SQLite数据库的方法,它按预期工作。 在数据库上找到条目时,我设置一个布尔值来显示欢迎消息-否则该布尔值将显示登录文本字段。
我认为我要执行以下操作:
<!-- User not in DB -->
<div ng-if="showLoginUI">
<div class="input">
<input type="password" placeholder="User ID" ng-model="userID"/>
</div>
</div>
我监视文本字段中的更改以保存用户输入,但是在上述示例中未注册任何操作。 这是我在文本字段上注册用户操作的方法。
$scope.$watch("userID", function (newVal, oldVal)
{
if (newVal !== oldVal) {
$scope.newUserID = newVal; // Not getting here
}
});
但是,当我从上面的示例中删除ng-if时,将注册用户事件。 在仍在文本字段上注册事件的同时,如何保持ng-if?
我试图在$ watch函数中添加$ timeout,但这也没有帮助。
发生这种情况是因为ngIf
指令创建了一个子$scope
..问题是您使用的是ng-model
而没有Dot Rule
或controller-as-syntax
。
Pankaj Parkar已在此问题中解释了整个问题。
因此,要使其工作,您必须创建一个新对象,例如:
$scope.model = {};
然后,像这样构建您的ng-model
:
ng-model="model.userID"
看一下这个简单的工作 演示 :
angular.module('app', []) .controller('mainCtrl', function($scope) { $scope.model = {}; $scope.$watch("model.userID", function(newVal, oldVal) { if (newVal !== oldVal) { $scope.model.newUserID = newVal; } }); });
<html ng-app="app"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script> </head> <body ng-controller="mainCtrl"> <button type="button" ng-click="showLoginUI = !showLoginUI">Hide/Show</button> <div ng-if="showLoginUI"> <div class="input"> <input type="password" placeholder="User ID" ng-model="model.userID" /> </div> </div> <div ng-if="model.newUserID"> <hr> <span ng-bind="'Working: ' + model.newUserID"></span> </div> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.