我在将输入框绑定到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";
,那么它会显示在页面加载的文本框中,但是当我修改文本框时,该值永远不会更新
答案 0 :(得分:1)
可能是因为您使用的是ng-if
而非ng-show
指令。
这是因为ng-if
从DOM中删除了元素,而ng-show
使用css规则来隐藏元素。
这是展示这个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
)则丢失其值。