我正在学习来自Java的Angular,我很难搞清楚这一点。我在第一个if语句中得到一个“ReferenceError:user is not defined”,但是在我的另一个控制器中,我正在以完全相同的方式声明一个变量,它工作正常。此错误的文档似乎试图使用超出范围或尚未声明的变量;这里的不一致在哪里?
以下是注入ng-view的表单:
<form role="form" ng-submit="controller.register()">
<div ng-show="controller.user.username.length > 20">Username must be 20 characters or less.</div>
<br>
<div ng-show="controller.user.username = null">Username is blank.</div>
<br>
<input type="text" name="username" ng-model="controller.user.username" placeholder="Choose a username." />
<br/>
<div ng-show="controller.user.password = null">Password is blank.</div>
<br>
<input type="password" name="password" ng-model="controller.user.password" placeholder="Choose a password." />
<input class="button" type="submit" value="Submit">
<div>{{controller.msg}}</div>
</form>
这是控制器的相关部分:
wishingWell.controller('register', function($http, $location, $rootScope) {
var noerrors = false;
var self = this;
self.user = {};
self.msg = undefined;
if (self.user.username != null && self.user.username.length <= 20 && self.user.password != null) {
noerrors = true;
}
self.register = function() {
if (noerrors) {
$http.post('register', user).success(function(response) {
if (response.data.code == "200") {
$rootScope.authenticated = true;
$location.path("/user-home");
} else {
msg = response.data.msg;
$location.path("/sign-up");
}
});
} else {
$location.path("/sign-up");
}
};
});
以下是以类似方式声明变量的登录控制器:
wishingWell.controller('navigation',
function($rootScope, $http, $location) {
var self = this;
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization: "Basic " + btoa(credentials.username + ":" + credentials.password)
} : {};
$http.get('user', {
headers: headers
}).then(function(response) {
if (response.data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback();
}, function() {
$rootScope.authenticated = false;
callback && callback();
});
}
authenticate();
self.credentials = {};
self.login = function() {
authenticate(self.credentials, function() {
if ($rootScope.authenticated) {
$location.path("/");
self.error = false;
} else {
$location.path("/login");
self.error = true;
}
});
};
});