Angular:通过控制器向partials中添加自定义脚本/css
Angular: Adding custom script/css to partials via controller
我试图通过控制器将自定义页面CSS/JS添加到我的部分,我已经为它创建了一个自定义指令,但当我使用它加载CSS时,它会得到我不想要的不必要的参数,当我使用它加载JS时,我的JS不会加载正确的时间(意味着在页面中编写的init函数之前被调用,留下错误)
指令
app.directive('head', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'E',
link: function(scope, elem){
var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
elem.append($compile(html)(scope));
scope.routeStyles = {};
$rootScope.$on('$routeChangeStart', function (e, next, current) {
if(current && current.$$route && current.$$route.css){
if(!Array.isArray(current.$$route.css)){
current.$$route.css = [current.$$route.css];
}
angular.forEach(current.$$route.css, function(sheet){
delete scope.routeStyles[sheet];
});
}
if(next && next.$$route && next.$$route.css){
if(!Array.isArray(next.$$route.css)){
next.$$route.css = [next.$$route.css];
}
angular.forEach(next.$$route.css, function(sheet){
scope.routeStyles[sheet] = sheet;
});
}
});
}
};
}
]);
<应用程序控制器/strong>
app.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/some/route/1', {
templateUrl: 'partials/partial1.html',
controller: 'Partial1Ctrl',
css: 'css/partial1.css'
})
.when('/some/route/2', {
templateUrl: 'partials/partial2.html',
controller: 'Partial2Ctrl',
css: ['css/partial2_1.css','css/partial2_2.css']
})
}]);
输出
CSS
<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="css/createtroll.css" class="ng-scope" href="css/partial2.css">