[英]Angular binding directive scope to controller scope
我正在为正在构建的应用程序创建一个忘记密码功能,因此我构建了一个功能,该功能将$ http请求发送到PHP资源,该资源向用户发送重置电子邮件。 当请求解决后,我将使用有角度的指令显示twitter twitterstrstr模式,该指令告诉用户其电子邮件是否已成功发送。
我遇到的问题是控制器和指令的范围似乎不同,因为更新控制器中的反馈不会更新指令的输出。
我的控制器:
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>
最后,我将所有这些都包含在绑定到注册控制器的注册模板中(注意:不要将忘记密码指令绑定到auth控制器),这是相关的位。
<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>
例如,如果将指令包装在控制器中,它将起作用:
<div ng-controller='Auth as auth'>
<div class='form-group'>
...
<a href='#' ng-click='auth.forgotPassword(reg.user.email)' title='Forgot password'>Forgot password?</a>
</div>
<forgot-password-directive></forgot-password-directive>
</div>
但是,此外,我将使用一种更简单的方法并随后定义指令:
function forgotPasswordDirective() {
return {
scope: false,
templateUrl: 'modules/auth/forgotPassword.html'
}
}
如果您熟悉Node,可以从以下位置克隆并运行示例: https : //github.com/masa67/NgBind 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.