根據當前頁面,我需要更改模板。我的問題是,如何通過頁面從controller
到directives
模板方法?如何將`controllers`狀態傳遞給`directive`模板函數?
這裏是我的嘗試:
UPDATE
我想這樣的,但仍然得到錯誤。將$route
注入directive
的正確方法是什麼?
根據當前頁面,我需要更改模板。我的問題是,如何通過頁面從controller
到directives
模板方法?如何將`controllers`狀態傳遞給`directive`模板函數?
這裏是我的嘗試:
UPDATE
我想這樣的,但仍然得到錯誤。將$route
注入directive
的正確方法是什麼?
您可以在您的指令聲明中調用$routeParams
,以在template
函數中使用它。
myApp.directive('galleryMenu', ['$routeParams', function($routeParams) {
return {
template: function() {
var page = $routeParams.page || 'homePage', // Define a fallback, if $routeParams doesn't have 'page' param
output;
switch (page) {
case "servicePage":
output = "<button>One Button</button><button>Two Button</button>";
break;
default:
case "homePage":
output = "<button>One Button</button>";
/*
NOTE: Or this other, it was confusing to tell which one to use
output = "<button>One Button</button><button>Two Button</button><button>Three Button</button>";
*/
break;
}
return output;
},
link: function(scope, element, attrs) {
/* ... */
}
}
}]);
如果您正在使用從$routeParams
ui-router
開關$stateParams
。
您需要從$ state.current獲取當前url,並且可以在templateProvider的幫助下傳遞給指令。
myApp.directive('galleryMenu', function() {
return {
templateProvider : getTemplate(template), //$scope.template need to pass
link : function (scope, element, attrs) {
console.log(scope.template);
}
}
from getTemplate你可以返回$ state.current。希望它能幫助你。
您可以請更新演示。我在模板方法中沒有定義'$ current'。 – user2024080
您是使用angular-ui路由器還是簡單的路由提供商 – ngLover
簡單的路由提供商,但我使用'$ route' - 在某些控制器上,它可以使用 – user2024080