动态 NG 控制器名称 [英] Dynamic NG-Controller Name
问题描述
我想根据我们加载的配置动态指定一个控制器.像这样:
解决方案 您想要做的是在调用其他任何指令之前运行另一个指令,从某个模型中获取控制器名称,删除新指令并添加 ng-controller
指令,然后重新编译该元素.
看起来像这样:
global.directive('dynamicCtrl', ['$compile', '$parse',function($compile, $parse) {返回 {限制:'A',终端:真的,优先级:100000,链接:功能(范围,元素){var name = $parse(elem.attr('dynamic-ctrl'))(scope);elem.removeAttr('dynamic-ctrl');elem.attr('ng-controller', name);$compile(elem)(范围);}};}]);
然后你可以在你的模板中使用它,就像这样:
<div dynamic-ctrl="'blankCtrl'">{{tyler}}</div>
使用这样的控制器:
global.controller('blankCtrl',['$scope',function(tyler){泰勒.泰勒 = '泰勒';tyler.tyler = '变色龙';}]);
可能有一种方法可以插入 dynamic-ctrl
的值 ($interpolate
) 而不是解析它 ($parse
),但由于某种原因我无法让它工作.
I want to dynamically specify a controller based on a config that we load. Something like this:
<div ng-controller="{{config.controllerNameString}}>
...
</div>
How do I do this in angular? I thought this would be very easy, but I can seem to find a way of doing this.
解决方案 What you want to do is have another directive run before anything else is called, get the controller name from some model remove the new directive and add the ng-controller
directive, then re-compile the element.
That looks like this:
global.directive('dynamicCtrl', ['$compile', '$parse',function($compile, $parse) {
return {
restrict: 'A',
terminal: true,
priority: 100000,
link: function(scope, elem) {
var name = $parse(elem.attr('dynamic-ctrl'))(scope);
elem.removeAttr('dynamic-ctrl');
elem.attr('ng-controller', name);
$compile(elem)(scope);
}
};
}]);
Then you could use it in your template, like so:
<div dynamic-ctrl="'blankCtrl'">{{tyler}}</div>
with a controller like this:
global.controller('blankCtrl',['$scope',function(tyler){
tyler.tyler = 'tyler';
tyler.tyler = 'chameleon';
}]);
There's probably a way of interpolating the value ($interpolate
) of the dynamic-ctrl
instead of parsing it ($parse
), but I couldn't get it to work for some reason.
这篇关于动态 NG 控制器名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!