Ken*_*nne 9 angularjs angularjs-directive angularjs-routing
我需要能够为不同的路由指定不同的布局,最好我希望能够在路由配置中的对象中定义布局和其他参数,并让它们在路由更改时传播.
这是我在当前项目中解决它的方式.
工作演示可在此处找到
如果您可以在$routeProvider.when(...)块中定义对象,如下所示:
路线定义:
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: 'MainCtrl',
resolve: {
interceptor: interceptWith('routeChangeInterceptor', {
stateClass: {
fullWidthLayout: true
}
})
}
});
Run Code Online (Sandbox Code Playgroud)
让它们传播并使用它来添加ng-class类似接口的类使用像这样的stateClass对象?
HTML:
<body state-class="{'full-width-layout': fullWidthLayout}"> ... </body>
<div class="some-class" state-class="{'some-class': someValue}"> ... </div>
Run Code Online (Sandbox Code Playgroud)
这是使用一个interceptWith(...)简单地注入服务并使用给定参数调用它的帮助器,但也可以使用这样的数组符号来实现
interceptor: ['serviceToInject', function(injectedService) { .. }];
Run Code Online (Sandbox Code Playgroud)
只有这样它才是DRYer.有关详细信息,请参阅演示.
//This interceptor is responsible for emiting an event on rootScope
.factory('routeChangeInterceptor', ['$rootScope', function($rootScope) {
var _prepare = function(state) {
$rootScope.$broadcast('data:broadcast-state', state);
};
return {
prepare: _prepare
};
}]);
Run Code Online (Sandbox Code Playgroud)
//This directive receives and $parses object/classname mappings,
//and it will add or remove the defined class for every mapping that is defined.
angular.module('broadcastState')
.directive('stateClass', ['$parse', function ($parse) {
var _linkFn = function link(scope, element, attrs) {
scope.$on('data:broadcast-state', function(e, state) {
//Set defaults
state = state || {};
state.stateClass = state.stateClass || {};
var classes = $parse(attrs.stateClass)(state.stateClass);
angular.forEach(classes,function(value,className) {
if(value && typeof value === 'boolean')
{
element.addClass(className);
}
else
{
element.removeClass(className);
}
});
});
}
return {
restrict: 'A',
link: _linkFn
};
}]);
Run Code Online (Sandbox Code Playgroud)
查看plnkr以了解更多信息.
| 归档时间: |
|
| 查看次数: |
6992 次 |
| 最近记录: |