【发布时间】:2015-06-06 10:40:46
【问题描述】:
我正在关注 this guide 以在我的 Angular 应用程序中实施身份验证,但我无法访问控制器内的模型。
在我的应用程序的某个地方,我像这样打开模态窗口:
loginModal().then(function() {
// Successful login, proceed to the page the user wants
return $state.go(toState.name, toParams);
}).catch(function() {
// Login failed, return home
return $state.go('home');
});
loginModal() 是一个服务,看起来像这样:
myApp.service('loginModal', function($modal, $localStorage) {
function assignCurrentUser(user) {
$localStorage.user = user;
return user;
}
return function() {
var instance = $modal.open({
templateUrl: '/partials/modals/login.html',
controller: 'LoginController',
windowClass: 'small'
});
return instance.result.then(assignCurrentUser);
};
});
当使用loginModal() 服务时,它会在包含/partials/modals/login.html 文件的HTML 的页面上打开一个模式窗口。这一切都完美无缺。您会注意到我还指定了要在模式中使用的控制器:LoginController。
LoginController 是这样写的:
myApp.controller('LoginController', function($scope) {
$scope.login = function() {
console.log($scope.user);
};
});
最后是模态窗口中使用的部分:
<form name="loginForm" novalidate method="post" ng-submit="login();">
<label>Email address
<input type="email" name="email" ng-model="user.email">
</label>
<label>Password
<input type="password" name="password" ng-model="user.password">
</label>
<input type="submit" value="Login">
</form>
问题是,当我填写表单(通过填充 user.email 和 user.password)并单击提交按钮时,我将 undefined 打印到控制台。
基本上,我的LoginController 中的$scope.login 函数确实会执行,但是$scope.user 属性是未定义的,即使它应该由模式窗口中的表单填充(使用ng-models) .
另外,如果我将{{user.email}} 放入模态模板,然后填充电子邮件字段,它确实会被打印出来。所以我知道双向数据绑定有效。
为什么我不能从控制器内的模式窗口访问 $scope 值?
【问题讨论】:
-
这个问题解决了吗,还是你还需要什么?
标签: javascript angularjs scope modal-dialog