I'm trying to read the variable accessCode
in my form in a Angular (1.6.8) function but I only get undefined
.
The HTML
<form ng-submit="redeem()" ng-controller="SubscriptionCtrl as subscription">
<input class="text-uppercase" type="number" ng-maxlength="6" placeholder="Indtast kode" ng-model="accessCode" />
<input type="submit" class="btn btn-dark-green" value="Indløs" />
</form>
The Angular JS
app.controller('SubscriptionCtrl', ['$scope', '$http', '$templateCache',
function ($scope, $http, $templateCache) {
$scope.redeem = function () {
console.log($scope.accessCode);
};
}]);
Any ideas why I can't read $scope.accessCode?
You don't have to revert your code back to using $scope
since using controller as syntax is better (See advantages). You have to bind not only your ng-model
but also your ng-submit
to your controller instance subscription
.
var app = angular.module('myApp', [])
app.controller('SubscriptionCtrl',
function() {
var subscription = this;
subscription.redeem = function() {
console.log(subscription.accessCode)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="SubscriptionCtrl as subscription">
<form ng-submit="subscription.redeem()">
<input class="text-uppercase" type="number" ng-maxlength="6" placeholder="Indtast kode" ng-model="subscription.accessCode" />
<input type="submit" class="btn btn-dark-green" value="Indløs" />
</form>
</div>
</div>