I'm encountering an issue with binding an input box to a controller in Angular. Despite following tutorials, the model never updates when I access the property or check the scope using AngularJS Batarang.
Upon form submission, $scope.licenceKey
remains empty!
<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;
});
};
The username directive (although its name needs updating to reflect its function)
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;
};
}
}
});
Despite entering text into the input, $scope.licenceKey
always remains empty. However, the custom validation on the input functions correctly.
It's worth noting that binding to Applying
for controlling view states does work!
Update
I found that by using
$scope.licenceForm.licenceKey.$modelValue
, I can retrieve the value. But why is this necessary?
Update 2
If I initially set $scope.licenceKey = "test";
, it displays in the textbox on page load. However, any modifications to the textbox do not update this value.