我对 Angular 的一个相当简单的问题感到困惑(因为我认为它很简单)。有时 Angular 让我觉得自己很蠢,因为我不可能做错什么可怕的事情。
接受这个 plnkr http://plnkr.co/edit/BmM9C5zjDAIfGTVzkU29?p=preview
HTML:
<body ng-app="app">
<div ng-controller="ASDF">
<div fb-login="doh" ng-click="exec()">CLICKY (should execute parent scope function but doesnt)</div>
</div>
</body>
Javascript:
angular.module('app', [])
.controller('ASDF', function($scope){
$scope.doh = function(d){
alert(d);
}
})
.directive('fbLogin', function(){
return {
restrict: 'A',
replace: false,
scope: {
done: '&fbLogin'
},
link: function(scope){
scope.exec = function(){
scope.done()('asdf');
};
}
}
});
这里发生了什么?
最佳答案
Isolate scope 在 1.2 版本中是完全隔离的(参见 https://github.com/angular/angular.js/commit/909cabd36d779598763cc358979ecd85bb40d4d7 )
fix($compile): make isolate scope truly isolate
Fixes issue with isolate scope leaking all over the place into other directives on the same element.
Isolate scope is now available only to the isolate directive that requested it and its template.
A non-isolate directive should not get the isolate scope of an isolate directive on the same element, instead they will receive the original scope (which is the parent scope of the newly created isolate scope).
Paired with Tobias.
BREAKING CHANGE: Directives without isolate scope do not get the isolate scope from an isolate directive on the same element. If your code depends on this behavior (non-isolate directive needs to access state from within the isolate scope), change the isolate directive to use scope locals to pass these explicitly.
// before
.directive('ngIsolate', function() { return { scope: {}, template: '{{value}}' }; });
// after
.directive('ngIsolate', function() { return { scope: {value: '=ngModel'}, template: '{{value}} }; });
现在唯一可行的方法是通过模板/templateUrl(在这种情况下使用 transclude,所以我不需要重新创建它):
angular.module('app', [])
.controller('ASDF', function($scope){
$scope.doh = function(d){
alert(d);
}
})
.directive('fbLogin', function(){
return {
restrict: 'A',
replace: false,
scope: {
done: '&fbLogin'
},
transclude: true,
template: '<div ng-transclude ng-click="exec()"></div>',
link: function(scope){
scope.exec = function(){
scope.done()('asdf');
};
}
}
});
关于javascript - Angular 1.2.16、隔离作用域、父函数和 ng-click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23355238/