3

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

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>'      
   }
   });

感谢马克解决这个问题:

    <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>'
};

})

- - - - - - - - - - - - - - - - - - - - - - -标记 - - --------------------------------------------------

这是笨蛋:

http://plnkr.co/edit/b6G2y3yqjhxpu059ZrWB

这是问题所在:

我将两个指令组合成一个超级指令。如果您转到 app.js,指令“selectAddNew”,从底部开始的第三行,您将看到:

......... action="openDialog(\'Front\')" ......

但这是硬编码的。我尝试了各种方法让它成为超级指令中的一个动作,但我最接近的是打开整个表单窗口的通用对话框。有任何想法吗?

4

2 回答 2

2

模板在编译阶段编译,此时someVarName不可用(它是指令范围的属性,尚未设置)。相反,在 compile 函数中,我们可以向 中添加一个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);
        }
    }
});

小提琴

于 2013-04-27T15:27:50.833 回答
0

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

于 2013-04-27T15:00:07.480 回答