gpt4 book ai didi

javascript - 在 AngularJS 中使用 $watch 获取用户输入文本不适用于 ng-if

转载 作者:行者123 更新时间:2023-12-02 14:24:01 25 4
gpt4 key购买 nike

我有一个使用 AngularJS、Monaca 和 OnsenUI 构建的跨平台应用程序。

我有一个登录 View ,它通过查询 SQLite 数据库来检查用户之前是否登录过。根据数据库中是否有数据,我向用户显示欢迎消息或显示登录文本字段。

我有一个查询 SQLite 数据库的方法,并且它按预期工作。当在数据库中找到条目时,我设置一个 bool 值来显示欢迎消息 - 否则 bool 值显示登录文本字段。

在我看来,我做了以下事情;

<!-- 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 的同时仍在文本字段上注册事件?

我尝试将 $timeout 添加到我的 $watch 函数中,但这也没有帮助。

最佳答案

发生这种情况是因为 ngIf 指令创建了一个子 $scope.. 问题是您使用的 ng-model 没有 点规则 Controller 作为语法

Pankaj Parkar 已经解释了整个问题。在这个question .

因此,要使其工作,您必须创建一个新对象,例如:

$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>

关于javascript - 在 AngularJS 中使用 $watch 获取用户输入文本不适用于 ng-if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38441365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com