Angularjs 在指令中使用控制器的最佳方法
我正在尝试制定一个指令,以便可以在不同的页面中重用视图。让我们称之为我的指令:Angularjs 在指令中使用控制器的最佳方法,angularjs,Angularjs,我正在尝试制定一个指令,以便可以在不同的页面中重用视图。让我们称之为我的指令: app.directive("myDirective", function() { . . . templateUrl: reuse.html, controller: function() { . . . }, controllerAs: ReuseCtrl }); 现在我想在page1.html和page2.html上使用这个指令
app.directive("myDirective", function() {
.
.
.
templateUrl: reuse.html,
controller: function() {
.
.
.
},
controllerAs: ReuseCtrl
});
现在我想在page1.html和page2.html上使用这个指令
<div>
<my-directive></my-directive>
</div>
最好的方法是在指令中调用控制器。例:
angular.module('directives', []).directive('directiveName', function() {
return {
restrict: 'AE',
templateUrl: 'views/myDirective.html',
controller: 'controllerNameCtrl'
}
})
指令是行为。如果您确实需要两个不同的控制器,那么创建两个不同的指令 但是,如果您只需要两个不同的控制器来访问它们的某些属性,例如$scope.books,那么最好将该参数传递到指令中 例如:
app.directive('myDirective', function() {
return {
scope: { books: '=' },
link: function(scope, elem, attrs) {
// use scope.books here
}
}
});
<my-directive books="model.books"></my-directive>
案例1怎么样?我想使用两个不同的控制器?这是一种特殊情况,因此您可以直接调用控制器。类似控制器的指令应该是上下文独立的,即根本不应该依赖父控制器。要使指令可用的任何内容都应该通过作用域参数传入
<div ng-controller="ReuseCtrl">
.
.
.
</div>
app.directive("myDirective", function() {
.
.
.
templateUrl: reuse.html,
controller: function() {
.
.
.
},
controllerAs: ReuseCtrl
});
angular.module('directives', []).directive('directiveName', function() {
return {
restrict: 'AE',
templateUrl: 'views/myDirective.html',
controller: 'controllerNameCtrl'
}
})
app.directive('myDirective', function() {
return {
scope: { books: '=' },
link: function(scope, elem, attrs) {
// use scope.books here
}
}
});
<my-directive books="model.books"></my-directive>