gpt4 book ai didi

javascript - Angular 形式绑定(bind)问题

转载 作者:行者123 更新时间:2023-12-03 11:26:46 25 4
gpt4 key购买 nike

我在将输入框绑定(bind)到 Angular 中的 Controller 时遇到一些问题。我已经按照在各种教程中看到的方式进行了设置,但是当我访问该属性或使用 AngularJS Batarang 检查范围时,我看到模型永远不会更新。

当我提交表单时,$scope.licenceKey 始终为空!

<div ng-app="licenceApp" ng-controller="licenceController">
<form name="licenceForm" ng-submit="applyKey()" novalidate>
<span ng-if="!Applying">
<input type="text" ng-model="licenceKey" ng-disabled="Applying" ng-model-options="{ debounce : { 'default' : 150 } }" username-available-validator required />
...

JS:

angular.module('licenceApp.controllers', [])
.controller('licenceController', function ($scope, licenceAPIservice, $filter) {
$scope.licenceKey = "";
$scope.Applying = false;
...
$scope.applyKey = function () {
$scope.Applying = true;

// $scope.licenceKey is always empty here!!
licenceAPIservice.applyKey($scope.licenceKey).then(function (data) {
console.log(data);

// Update model once we have applied the key
$scope.update();
}, function () {
$scope.Applying = false;
});
};

还有用户名指令(我需要更改名称以反射(reflect)其功能,但还没有)

angular.module('licenceApp.directives', [])
.directive('usernameAvailableValidator', function ($http, $q, licenceAPIservice) {
return {
require: 'ngModel',
link: function ($scope, element, attrs, ngModel) {
ngModel.$asyncValidators.usernameAvailable = function (username) {
var deferred = $q.defer();

licenceAPIservice.validateKey(username).then(function (data) {
if (data.data) {
deferred.resolve();
}
else {
deferred.reject();
}
}, function () {
deferred.reject();
});

return deferred.promise;
};
}
}
});

当我在任何地方访问 $scope.licenceKey 时,即使我输入了输入,它也始终为空,尽管我对输入进行的自定义验证工作正常

请注意,有趣的是,当我绑定(bind)到 Applying 来控制有效的 View 状态时!

更新

如果我使用$scope.licenceForm.licenceKey.$modelValue,我可以获取该值,但我不明白为什么这是必要的?

更新2

此外,如果我最初设置 $scope.licenceKey = "test"; ,那么它会在页面加载时显示在文本框中,但当我修改文本框时,该值永远不会更新

最佳答案

这可能是因为您使用的是 ng-if 而不是 ng-show 指令。

这是因为 ng-if 从 DOM 中删除元素,而 ng-show 使用 CSS 规则隐藏元素。

这是一个 fiddle 演示 http://jsfiddle.net/q9rnqju5/ .

HTML

<div ng-app="app">
<div ng-controller="controller">
<div ng-show="!applying1">
<input ng-model="value1" />
<button ng-click="apply1()">Submit</button>
</div>
<div ng-if="!applying2">
<input ng-model="value2" />
<button ng-click="apply2()">Submit</button>
</div>
</div>
</div>

JS

var app = angular.module("app", []);

app.controller("controller", ["$scope", "$timeout", function($scope, $timeout) {
$scope.apply1 = function() {
$scope.applying1 = 1;
$timeout(function() {
console.log($scope.value1);
$scope.applying1 = 0;
}, 1000);
};
$scope.apply2 = function() {
$scope.applying2 = 1;
$timeout(function() {
console.log($scope.value2);
$scope.applying2 = 0;
}, 1000);
};
}]);

您可以看到提交后,第一个输入(使用 ng-show)保留其值,而第二个输入(使用 ng-if)丢失其值。

关于javascript - Angular 形式绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26887542/

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