我已经创建了一个具有独立作用域的指令my-directive,但它似乎能够访问属性div1 of $rootScope和其父范围$scope of controller1的property div2。
我遗漏了什么?
Javascript:
angular.module('app', [])
.controller('controller1', ['$scope',
function ($scope) {
}])
.directive('myDirective', [
function () {
return{
restrict: 'A',
replace: true,
scope: {
myDirective:'='
}
};
}]);HTML:
<body>
<div id="1" ng-app="app" ng-init="div1='div1'">
<div id="2" ng-controller="controller1" ng-init="div2='div2'">
<div id="4" my-directive="value" ng-init="div4='div4'">
{{div4}}<br/>
{{div1}}<br/>
{{div2}}<br/>
</div>
</div>
</div>
</body>输出:
div4
div1
div2发布于 2014-06-24 06:56:04
作用域是在指令的模板中隔离的。给您的指令一个模板或编写一个链接函数,您将看到范围是孤立的。当您访问指令作用域的祖先时,这发生在指令之外,然后解析的html将被“排除”到您的指令模板中,否则该模板是空的。
不过,这是一个有趣的问题。直到现在,我才意识到省略指令的模板实际上与在指令定义中包含transclude: true, template: '<div ng-transclude></div>'是一样的。
虽然您没有包含这些属性中的两个,但实际上是这样做的:
.directive('myDirective', [
function () {
return{
restrict: 'A',
replace: true,
transclude: true,
template: '<div ng-transclude></div>',
scope: {
myDirective:'='
}
};
}]);还要注意,myDirective: '='应该是myDirective: '@',因为它只是一个字符串。
发布于 2014-06-24 07:41:41
您应该在指令中使用transclude函数,否则值将绑定到父作用域。检查这个:http://pucksart.com/transclude-big-mistery/
https://stackoverflow.com/questions/24380060
复制相似问题