我正在尝试构建一个指令,负责向声明它的元素添加更多指令.例如,我想构建一个负责添加的指令datepicker,datepicker-language和ng-required="true".
如果我尝试添加这些属性然后使用$compile我显然会生成一个无限循环,所以我正在检查我是否已经添加了所需的属性:
angular.module('app')
.directive('superDirective', function ($compile, $injector) {
return {
restrict: 'A',
replace: true,
link: function compile(scope, element, attrs) {
if (element.attr('datepicker')) { // check
return;
}
element.attr('datepicker', 'someValue');
element.attr('datepicker-language', 'en');
// some more
$compile(element)(scope);
}
};
});
Run Code Online (Sandbox Code Playgroud)
当然,如果我没有$compile元素,那么将设置属性但是指令不会被引导.
这种方法是正确的还是我做错了?有没有更好的方法来实现相同的行为?
UDPATE:鉴于这$compile是实现这一目标的唯一方法,有没有办法跳过第一个编译传递(该元素可能包含几个子节点)?也许通过设置terminal:true?
更新2:我已经尝试将指令放入一个select元素中,正如预期的那样,编译运行两次,这意味着预期option的数量是预期的两倍.
javascript model-view-controller mvvm angularjs angularjs-directive
我正在尝试为包含的模板动态分配控制器,如下所示:
<section ng-repeat="panel in panels">
<div ng-include="'path/to/file.html'" ng-controller="{{panel}}"></div>
</section>
Run Code Online (Sandbox Code Playgroud)
但Angular抱怨说这{{panel}}是不确定的.
我猜,{{panel}}是不是定义尚未(因为我可以附和了{{panel}}在模板中).
我已经看到很多人设置ng-controller等于变量的例子如下:ng-controller="template.ctrlr".但是,如果没有创建重复的循环循环,我无法弄清楚如何{{panel}}在ng-controller需要时获得可用值.
PS我也尝试ng-controller="{{panel}}"在我的模板中设置(认为它必须已经解决),但没有骰子.
自解释小提琴:http://jsfiddle.net/5FG2n/1/
假设我有两个控制器的视图,一个包含另一个.外部控制器是静态的,但我需要根据外部的范围变量设置内部控制器.范围变量将是内部控制器的名称作为字符串(例如'InnerCtrl').
这是观点:
<div ng-app='app' ng-controller='OuterCtrl'>
<div ng-controller='dynamicCtrl'>
{{result}}
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
这是不正确的模块:
angular.module('app', [])
.controller('OuterCtrl', ['$scope',
function($scope) {
// Instead of hard coding the controller here,
// how do I resolve the string 'InnerCtrl' to the
// controller function defined below, so it can be
// assigned to this dynamicCtrl property?
$scope.dynamicCtrl = function($scope) {
$scope.result = 'not working yet';
};
//eg:
//$scope.dynamicCtrl = resolveCtrl('InnerCtrl');
}
])
.controller('InnerCtrl', ['$scope', 'service',
function($scope, service) {
$scope.result = …Run Code Online (Sandbox Code Playgroud)