动态NG-控制器名称 [英] Dynamic NG-Controller Name
问题描述
我要动态地指定基于我们加载一个配置的控制器。事情是这样的:
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.
推荐答案
您想要做的是有另一个指令运行其它任何调用之前,一些模型得到的控制器名称中删除新指令并添加 NG-控制器
指令,然后重新编译元素。
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.
这看起来是这样的:
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';
}]);
有可能是插值价值的一种方式( $插值
)的动态CTRL 的而不是解析它(
$解析
),但我无法得到它出于某种原因。
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屋!