使用具有公共作用域的指令作为隔离作用域



一段时间前,我编写了一个自定义指令,现在它在代码中的许多地方都被使用(无法再更改它(。

它有一个公共范围,直到今天都很好。现在,我想在同一控制器作用域(父作用域(内使用同一指令两次,但需要每个指令(子作用域(都有自己的变量(如隔离作用域(,并且彼此不匹配。

是否可以插入此指令并显式声明使用隔离作用域,即使它最初是用公共作用域创建的?或者可能是一种将其限制在父控制器内的方法?或者还有其他方法吗?

前任。

// Panel directive
angular.directive('panel', function(){
return {
restrict: 'E',
templateUrl: 'panel.html',
replace: true,
transclude: true
}
});
// Parent directive (include more than one 'panel' directives)
angular.directive('parentDirektive'), function() {
return {
restrict: 'E',
templateUrl: 'parent.html',
replace: true,
transclude: true,
scope: {},
controller: function($scope) {
// I want to set different value for this variable
// in each 'panel' direktive I add in 'parent.html'.
$scope.headline = 'this.should.be.unique.in.each.panel.directive';
}
}
});

parent.html

我想以某种方式设置"scope.headline"的值此处出现的每个面板都不同(比如隔离每个指令中的变量(?!但不能在声明中将范围更改为孤立只有在这种情况下才需要它。

<html>
<body>
<!-- I want to display 'Title: First Panel' -->
<panel></panel>
<!-- I want to display 'Title: Second Panel' -->
<panel></panel>
</body>
</html>

panel.html

<html>
<body>
<h1>Title: {{$scope.headline}}</h1>
</body>
</html>

例如,最好使用一个独立的作用域。

var myApp = angular.module('myApp');
myApp.directive('myDirective', () => ({
template: `<div>{{vm.aaa}}</div>`,
controller: 'myDirectiveCtrl',
controllerAs: 'vm',
restrict: 'EA',
transclude: true,
scope: {
aaa: "=" // use if you want to pass varuble to the directive
},
bindToController: true,
}));
myApp.controller('myDirectiveCtrl', function () {
console.log(this.aaa); // will come beck undefind
vm.$postLink = () => {
console.log(this.aaa); // return the passed value
};
});

每个指令都有自己的范围

<my-directive aaa="'77'"></my-directive>
<my-directive aaa="'99'"></my-directive>

被告知控制器将不会在收发区上工作

一个选项是为每个组件添加一个控制器:

<html>
<body>
<!-- I want to display 'Title: First Panel' -->
<panel ng-controller="firstPanelController"></panel>
<!-- I want to display 'Title: Second Panel' -->
<panel ng-controller="secondPanelController"></panel>
</body>
</html>

ng-controller指令创建一个新的继承作用域,控制器可以在该作用域上放置超派生父作用域属性的属性。

最新更新