【发布时间】:2015-07-16 13:23:41
【问题描述】:
我遇到了一些关于隔离范围的问题。我有一个需要在很多地方使用的指令,它的控制器有一些指令的辅助函数。该指令确实创建了隔离范围,但模板引用了父范围。下面是一个演示该问题的插件
http://plnkr.co/edit/LQnlSjMHeatMkmkYZyfk
$scope.text = "test";
是为了演示该属性在隔离作用域内不发生变化,而是指向父作用域。由于这个问题,我无法为每个隔离范围调用辅助函数。我希望我能够正确地描述我的问题。
下面是代码
HTML:
<body ng-controller="MainCtrl">
<div transfer-box style="">
{{text}}
<div ng-if="refresh" ></div>
{{refresh}}
</div>
<div transfer-box style="">
{{text}}
<div ng-if="refresh" ></div>
{{refresh}}
</div>
</body>
Javascript:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.text = 'World';
console.log("parent scope id "+ $scope.$id);
});
app.directive('transferBox', function() {
return {
restrict: 'EA',
xreplace: true,
transclude: true,
scope:true,
template: '<div class="container-fluid" style="height:100%" ng-transclude></div>',
controller:'transferBoxCtrl'
};
})
app.controller('transferBoxCtrl',['$scope',function($scope){
console.log($scope.$id);
$scope.refresh = true;
$scope.text = "test";
}])
【问题讨论】:
-
你能把所有相关代码都放在帖子里吗?
-
您正在对指令使用外部控制器!坏,坏主意!你应该为指令创建一个指令控制器!
-
能否请您编辑一下 plunk 以便我能正确理解。
标签: javascript angularjs angularjs-scope