Подписываясь на текущую страницу, мне нужно изменить шаблон. мой вопрос в том, как передать current
страницу от controller
к методу шаблонов directives
?
вот моя попытка:
var myApp = angular.module('myApp', []);
myApp.controller('main', function ($scope) {
$scope.template = "homePage";
});
var getTemplate = function (page) { //i need $scope.template as params
if (page == "homePage") {
return "<button>One Button</button>"
}
if (page == "servicePage") {
return "<button>One Button</button><button>Two Button</button>"
}
if (page == "homePage") {
return "<button>One Button</button><button>Two Button</button><button>Three Button</button>"
}
}
myApp.directive('galleryMenu', function () {
return {
template : getTemplate(template), //$scope.template need to pass
link : function (scope, element, attrs) {
console.log(scope.template);
}
}
})
ОБНОВИТЬ
Я так стараюсь, но все еще получаю ошибку. Каков правильный способ ввода $route
в directive
?
var galleryMenu = function ($route, $location) {
return {
template : function () {
console.log($route.current.className); //i am not getting!
},
link : function () {
}
}
}
angular
.module("tcpApp", ['$route', '$location'])
.directive('galleryMenu', galleryMenu);
Вы можете вызвать $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) {
/* ... */
}
}
}]);
Если вы используете переключатель ui-router
от $routeParams
до $stateParams
.
Вы должны получить текущий url из $ state.current и можете перейти в директиву с помощью templateProvider.
myApp.directive('galleryMenu', function () {
return {
templateProvider : getTemplate(template), //$scope.template need to pass
link : function (scope, element, attrs) {
console.log(scope.template);
}
}
из getTemplate вы можете вернуть $ state.current. надеюсь, это поможет вам.
$current
не определено в методе шаблона.