【发布时间】:2015-01-14 23:00:10
【问题描述】:
自从几个月前学习 Angular 以来,我的印象是 `directives 是特殊功能,可以通过以下两种方式之一在 HTML 标签中放置关键字来激活 - 要么作为元素, 作为一个属性。
例如:
<my-directive>Something</my-directive>
或
<div my-directive></div>
但是,in a Git project I came across,我看到一个指令以完全不同的方式使用,我不明白它是如何工作的。
该指令应该是通过在 ui-router 中的 .state() 函数中添加一个键值 css: {} 来激活的。
例如:
.state('state1', {
url: '/state',
controller: 'StateCtrl',
templateUrl: 'views/my-template.html',
data: {
css: 'styles/style1.css'
}
})
这个“指令”是如何工作的?
---------
从 Git 项目复制的指令的 Javascript 源代码,因此保留在此问题中:
/**
* @author Manuel Mazzuola
* https://github.com/manuelmazzuola/angular-ui-router-styles
* Inspired by https://github.com/tennisgent/angular-route-styles
*/
'use strict';
angular
.module('uiRouterStyles', ['ui.router'])
.directive('head', ['$rootScope', '$compile', '$state', '$interpolate',
function($rootScope, $compile, $state, $interpolate) {
return {
restrict: 'E',
link: function(scope, elem){
var start = $interpolate.startSymbol(),
end = $interpolate.endSymbol();
var html = '<link rel="stylesheet" ng-repeat="(k, css) in routeStyles track by k" ng-href="' + start + 'css' + end + '" >';
elem.append($compile(html)(scope));
// Get the parent state
var $$parentState = function(state) {
// Check if state has explicit parent OR we try guess parent from its name
var name = state.parent || (/^(.+)\.[^.]+$/.exec(state.name) || [])[1];
// If we were able to figure out parent name then get this state
return name && $state.get(name);
};
scope.routeStyles = [];
$rootScope.$on('$stateChangeStart', function (evt, toState) {
// From current state to the root
scope.routeStyles = [];
for(var state = toState; state && state.name !== ''; state=$$parentState(state)) {
if(state && state.data && state.data.css) {
if(!Array.isArray(state.data.css)) {
state.data.css = [state.data.css];
}
angular.forEach(state.data.css, function(css) {
if(scope.routeStyles.indexOf(css) === -1) {
scope.routeStyles.push(css);
}
});
}
}
scope.routeStyles.reverse();
});
}
};
}
]);
【问题讨论】:
-
my-template.html 是什么样的?
-
@Angad 显然没关系。重要的是您将
css:放在.state函数中。顺便说一句,我添加了一个指向我所指的 Git 的链接。抱歉我一开始忘记了
标签: angularjs angularjs-directive attributes angular-ui-router