我正在构建一个简单的 angularjs 应用程序,我正在尝试在不刷新页面的情况下实现登录。
我在做什么
在初始化时,ng-include 加载/set/save。/set/save 得到了 <a fblogin>Login with Facebook</a>
在里面。因此,当单击该指令时,它会打开一个窗口,当该窗口关闭时,它应该更改 ng-include 的 src。
问题
当指令在 ng-include 中使用时(ng-include src 在 init 上有默认值),没有任何反应(控制台中没有错误,什么都没有),但是当我将指令放在 ng-include 之外时它正在工作很好(见下面的 HTML 代码)
HTML:
<div id="set-creator" ng-controller="SetCtrl">
........
<div id="saveModal" class="reveal-modal" data-reveal>
<a href fblogin>testCase</a>
// ^this is working
//but if the directive is inside ng-include, it's not working
<ng-include src="saveTemplate"></ng-include>
<a class="close-reveal-modal">×</a>
</div>
</div>
指令:
App.directive('fblogin', function() {
return {
transclude: false,
link: function(scope, element, attrs) {
element.click(function() {
var win = window.open("/auth/facebook", 'popUpWindow', 'centerscreen=true');
var intervalID = setInterval(function() {
if (win.closed) {
scope.saveTemplate = '/set/continue';
scope.$apply();
clearInterval(intervalID);
}
}, 100);
});
}
};
});
Controller :
App.controller("SetCtrl", ["$scope", "SetHolder",
function($scope, SetHolder) {
$scope.saveTemplate = '/set/save';
$scope.test = "loaded";
}
]);
和/设置/保存
You need to be logged in order to save the set.
<br />
<a fblogin>Login with Facebook</a>
最佳答案
这是一个有效的插件:http://plnkr.co/edit/ilVbkHVTQWBHAs5249BT?p=preview
你因为在作用域上使用原始值而陷入困境。
- 当您将
fblogin
放在ngInclude
之外时,它在 Controller 的相同范围内。 ngInclude
总是创建一个新的子作用域,因此其中的任何指令都在子作用域
上。
来自Understanding Scopes wiki:
Scope inheritance is normally straightforward, and you often don't even need to know it is happening... until you try 2-way data binding (i.e., form elements, ng-model) to a primitive (e.g., number, string, boolean) defined on the parent scope from inside the child scope.
It doesn't work the way most people expect it should work. What happens is that the child scope gets its own property that hides/shadows the parent property of the same name. This is not something AngularJS is doing – this is how JavaScript prototypal inheritance works.
New AngularJS developers often do not realize that ng-repeat, ng-switch, ng-view and ng-include all create new child scopes, so the problem often shows up when these directives are involved.
This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models.
在你的情况下发生的是 scope.saveTemplate = '/set/continue';
只是在子作用域上创建一个变量,它隐藏了 scope.saveTemplate
父范围( Controller )。
关于javascript - ng-include 中的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21369730/