[英]Is it possible to pass in a custom controller into custom directive?
是否可以將自定義控制器傳遞給自定義指令,以便能夠在具有不同控制器的頁面上使用自定義指令 ?
我無法在docs.angularjs.org上找到解決方案
將帖子
假設我們有以下指令的定義:
angular.module('myApp', [])
.controller('myDirectiveController', function ($scope) {
$scope.name = 'there, dude';
})
.directive('myDirective', function () {
return {
restrict: 'E',
replace: true,
template: '<div>Hello {{name}}!</div>',
controller: 'myDirectiveController' // can i overwrite it outside this code?
};
});
我可以簡單地覆蓋指令的控制器而不觸及指令的源代碼本身嗎?
將自定義控制器與一個HTML模板一起使
然后將您的數據從該頁面傳遞給指令。
並在指令中指定的HTML模板中使用該數據,或者您也可以在指令中編寫控制器。
.controller('myController', function () {
// write business logic here
// take some data which you want to use in directive
});
然后通過HTML傳遞給指令
使用該數據,
.directive('dir', function () {
return {
scope: {
// collect your data and use it in link
}
};
});
也許不是像你一樣在指令中定義控制器,你可以把它放在html模板中,如:
.directive('myDirective', function () {
return {
restrict: 'E',
replace: true,
scope: {
ctrl: '='
},
template: '<div ng-controller="{{ctrl}}">Hello {{name}}!</div>'
};
});
然后我認為您將能夠使用如下指令:
<my-directive ctrl="myDirectiveController"></my-directive>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.