从控制器添加自定义指令

时间:2015-06-26 14:04:48

标签: javascript angularjs angularjs-directive

我知道Controller不应该添加HTML及其指令作业。不幸的是,我目前无法管理它。

这是我的工作。 submit()是来自模板的电话,我感到很惭愧,因为我知道我做错了:

/*in my Controller */       

    $scope.widget = widget;
    $scope.ContentList =['array','graph','nevermind']
    $scope.form = {
        name: widget.name,
        id: widget.id,
        content: widget.content
    };

 $scope.submit = function() {
    angular.extend(widget, $scope.form);
    $modalInstance.close(widget);

    $timeout(function(){$scope.ajouterDirective();},100); //THIS SUCK HARD !
};

$scope.ajouterDirective = function(){
    var idWid = $scope.widget.id;
    var directive = getDirectiveHtmlCode($scope.widget.content); // return sth like '<my-custom-directive></my-custom-directive>'
    var compiled = $compile(directive)($scope);
    $('#widget'+idWid).append(compiled); // this suck two
}

有人可以告诉我/给出一个链接,解释如何正确地做到这一点吗?

感谢

--- Edit-- 表格的模板(非常简化)

<form name="_form" class="form-horizontal" ng-submit="submit(_form)">
 Name: <input name="name" type="text" ng-model="form.name" class="form-control" />
Content : <select name="content" ng-model="form.content" class="form-control">
<option ng-repeat="value in ContentList" value="{{value}}">{{value}}</option>
</select>
</form>

1 个答案:

答案 0 :(得分:1)

我会选择这样的事情:

HTML:

  <input type="text" ng-model="widgetCustomName">
  <select ng-model="widgetName" ng-options="widget.directiveName as widget.name for widget in widgets">
  </select>
  <button ng-click="addWidget()">Add directive</button>

  <!--  I'll repeat for each widgets placed by the user  -->
  <div ng-repeat="widget in placedWidgets">
    <h2>{{widget.customName}}</h2>
    <!--  here i'll use the directive according to the widget technical name -->
    <div ng-switch on="widget.widget">
      <mywidget1 ng-switch-when="mywidget1">Widget1</mywidget1>
      <mywidget2 ng-switch-when="mywidget2">Widget2</mywidget2>
      <div ng-switch-default>Crap you didn't select a widget</div>
    </div>
  </div>

控制器:

//We will look through this collection to display our widgets
$scope.placedWidgets = [];
//We define here the widgets availables in the select. name is a display name and directiveName the name of the associated directive.
$scope.widgets = [{
  "name" : "Widget1",
  "directiveName" : "mywidget1"
},{
  "name" : "Widget2",
  "directiveName" : "mywidget2"
}]

//This will be the function adding a widget in the collection according to the user inputs.
$scope.addWidget = function(){
  $scope.placedWidgets.push({
    "customName":$scope.widgetCustomName,
    "widget":$scope.widgetName
  })
}

以下是关联的plunker。 我希望这些评论足以作为解释,但如果您需要更多信息,请随意提问。