【发布时间】:2014-11-12 12:55:32
【问题描述】:
我在将输入框绑定到 Angular 中的控制器时遇到了一些问题。正如我在各种教程中看到的那样,我已经进行了设置,但是当我访问属性或使用 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;
});
};
还有用户名指令(我需要更改名称以反映其功能但还没有)
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 时,即使我输入了输入,它也总是为空,尽管我对输入的自定义验证工作正常
请注意,有趣的是,当我绑定到 Applying 以控制有效的视图状态时!
更新
如果我使用$scope.licenceForm.licenceKey.$modelValue,我可以得到价值,但我不明白为什么这是必要的?
更新 2
另外,如果我最初设置$scope.licenceKey = "test";,那么它会在页面加载时显示在文本框中,但是当我修改文本框时该值永远不会更新
【问题讨论】:
-
如果删除
ng-model-options属性会怎样?我们可以看看你的验证器管道username-available-validator -
@RahilWazir 嘿,不幸的是,删除
ng-model-options不会改变功能。我按照您的要求添加了指令代码。 -
所以验证对您有用吗?确保验证不应处于待处理状态。
-
验证工作正常,问题是当我提交表单时,我的提交代码使用
$scope.licenceKey,但始终为空! -
@RahilWazir 使用 Batarang 它显示 licenceKey 已设置,但在子范围内(不确定原因或方式)
标签: javascript angularjs