【发布时间】:2015-12-02 05:01:14
【问题描述】:
我正在为我正在构建的应用程序创建忘记密码功能,因此我构建了一个向 PHP 资源发送 $http 请求的函数,该资源向用户发送重置电子邮件。当请求解决后,我会显示一个 twitter bootstrp 模式,它使用一个角度指令告诉用户他们的电子邮件是否已成功发送。
我遇到的问题是控制器和指令的范围似乎不同,因为更新控制器中的反馈不会更新指令的输出。
我的控制器:
angular
.module('enigma.auth')
.controller('Auth', Auth);
Auth.$inject = ['authFactory'];
function Auth(authFactory) {
var auth = this;
auth.forgotPassword = forgotPassword;
auth.forgotPasswordFeedback = '';
function forgotPassword(email) {
if(email) {
authFactory.forgotPassword({ email: email })
.then(function(res) {
auth.forgotPasswordFeedback = res.message; // auth.forgotPasswordFeedback is set to the correct value now, however this isn't reflected in the directive.
$('#forgotPassword').modal();
});
}
};
}
我的指令:
angular
.module('enigma.forgotPasswordDirective', [])
.directive('forgotPasswordDirective', forgotPasswordDirective);
function forgotPasswordDirective() {
return {
bindToController: true, // I thought this told the directive to use the controllers scope instead of an isolated scope...
controller: 'Auth',
controllerAs: 'auth',
templateUrl: 'modules/auth/forgotPassword.html'
}
}
模板:
<div class='modal fade' id='forgotPassword'>
<div class='modal-dialog'>
<div class='modal-content'>
<button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>×</span></button>
<div class='row'>
<div class='col-xs-12'>
<h3>Password Recovery</h3>
<p>
{{auth.forgotPasswordFeedback}} <!-- this value is never updated :( -->
</p>
<p>
<button class='btn btn-primary' data-dismiss='modal'>Close</button>
</p>
</div>
</div>
</div>
</div>
</div>
最后,我将所有这些都包含在绑定到注册控制器的注册模板中(注意:不要将忘记密码指令绑定到身份验证控制器),这是相关位。
<div class='form-group'>
<label for='email'>Email:</label>
<input class='form-control' name='email' ng-model='reg.user.email' required type='email' ng-blur='reg.alreadyRegistered()' />
<div ng-messages='reg.regForm.email.$error' ng-if='reg.regForm.email.$dirty'>
<div class='error' ng-message='userExists'>This user already exists. <a href='#' ng-click='auth.forgotPassword(reg.user.email)' title='Forgot password' ng-controller='Auth as auth'>Forgot password?</a></div>
</div>
</div>
...
<forgot-password-directive></forgot-password-directive>
【问题讨论】:
-
您目前使用的是哪个版本的 Angular? bindToController 在 1.4 中更改
-
为什么要为指令和控制器提供单独的模块?
-
因为忘记密码需要在多个控制器中使用。 Authentication Ctrl 用于登录,Registration Ctrl 在注册时使用。
-
我认为您仍然需要定义您的范围内需要哪些变量,或者使用新的 1.4 bindToController 方法。如果您将 bindtoController 更改为
{forgotPasswordFeedback: '='},它会执行您期望的双向绑定吗? -
No 使用 bindToController 时没有变化:{ forgotPasswordFeedback: '=' }
标签: angularjs angularjs-directive angularjs-scope