AngularJS - 将ng-controller名称转换为指令变量

时间:2013-04-27 14:35:19

标签: angularjs

如果我在指令模板中有一个带有ng-controller属性值的div,我该如何将其更改为变量:

original html : <div ng-controller="HomeController"> ..... </div>

directive: <my-directive some-var-name="HomeController"> ....</my-directive>

.directive('MyDirective', function(){
  return {
   .....
   scope:
   {
     someVarName : "????"  <-- what type? "=", "@", "&" : none seem to work
   },
   template: '<div ng-controller="someVarName">.....</div>'      
   }
   });

感谢Mark解决此问题:

    <select-add-new  select-model="$parent.selectedFrontAxle" text="add new" 
             select-phrase="Front Axle Type" preselected-filter="Front" 
             label-name="Front Axle" open-dialog="Front" 
             select-options="axleTypes" var-ctrl="AxleTypesCtrl"></select-add-new>

  .directive('selectAddNew', function () {
   return {
    replace: true,
    restrict: "E",        
    scope: {
        selectModel: "=",
        selectOptions:"=",
        labelName: "@",
        preselectedFilter: "@",
        selectPhrase: "@",
        text: "@"
    },
    compile: function(tElement, attrs) {
        var div = tElement.find('#ctrlId');
        div.attr('ng-controller', attrs.varCtrl);
    },
    template: '<div>' + 
              '<div class="local-label">{{labelName}}: </div>' +
              '<name-value-select-control  select-phrase="{{selectPhrase}}" selected-item="selectModel" preselected-filter="{{preselectedFilter}}" options="selectOptions"></name-value-select-control>' +
              '<div id="ctrlId">' +
              '<div txt-add-new text="{{text}}" action="openDialog(\'Front\')" style="display: inline-block"></div>' +
              '</div>' +
              '</div>'
};

})

--------------------------------------------- Mark- -------------------------------------------------- ---

以下是plunker:

http://plnkr.co/edit/b6G2y3yqjhxpu059ZrWB

以下是问题:

我将两个指令合并为一个超级指令。如果你去app.js,指令'selectAddNew',你会看到从底部开始的第三行:

......... action =“openDialog(\'Front \')”..................

但这是硬编码的。我尝试了每一种方式使它成为超级指令中的一个动作,但我最接近的是打开整个表单窗口的公共对话框。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

模板在编译阶段编译,此时someVarName不可用(它是指令范围的属性,尚未设置)。相反,在编译函数中,我们可以向ng-controller添加div属性,并将其设置为some-var-name属性的值:

app.directive('myDirective', function() {
    return {
        restrict: 'E',
        template: '<div>....</div>',
        compile: function(tElement, attrs) {
            var div = tElement.find('div');
            div.attr('ng-controller',attrs.someVarName);
        }
    }
});

Fiddle

答案 1 :(得分:0)

我认为您正在寻找@:scope:{someVarName:'@'},template:'<div>Hello {{someVarName}}</div>