2016-07-06 23 views
1

我的問題是我的指令不顯示模板。我通過「$ sce.trustAsHtml(taskDirective)」「$ compile(taskDirective)($ scope)」在我的控制器中添加了具有特定名稱的html標記 。調用指令 內的控制器功能。但模板沒有顯示出來。角度指令不會渲染模板,在控制器中動態添加html後

進出口使用的$ stateProvider,它調用「TaskDetailCtrl」有一定的HTML。

有人可以幫忙嗎?

謝謝+

控制器:

app.controller("TaskDetailCtrl", function ($scope, $state, $stateParams, $sce, $compile) { 

    cur_task = $stateParams.newTask; 
    $scope.title = cur_task.title; 
    var taskDirective = "<" + cur_task.type + "taskdirective" + "></" + cur_task.type + "taskdirective" + ">"; 
    $scope.showTask = $sce.trustAsHtml(taskDirective); 
    $compile(taskDirective)($scope); 

}); 

指令:

app.directive('clicktaskdirective', function() { 
    return { 
     restrict: 'E', 
     template: '<ion-content style="padding: 20px;" class="text-center"><br><br><h1>{{taskTitle}}</h1><br><br><h4>{{taskText}}</h4><br><br><button class="button button-block button-stable" ng-click="start()">Stimmt!</button></ion-content>', 
     controller: function ($scope, $state, $stateParams) { 

      console.log("This is showing up!") 
     } 
    } 
}); 

HTML:

<div ng-bind-html="showTask"></div> 

回答

1

$ sce.trustAsHtml and ng-bind-html並不意味着用指令構建HTML。這種技術將無法工作。

這是因爲角通過首先編譯然後鏈接。請參閱conceptual overview以獲得很好的解釋。

簡而言之,在鏈接在trustAsHtml中定義的HTML時,角度編譯(因此理解)指令已爲時過晚。

爲了動態添加HTML,您應該查看$ compile服務(和/或指令)。 Docs are here

雖然我加入了以下有關問題的解決方案:

1. Make the below directive which will compile and append the directive to the element where we specified it. 

    app.directive('compile', function($compile) { 
     // directive factory creates a link function 
     return function(scope, element, attrs) { 
     scope.$watch(
      function(scope) { 
      // watch the 'compile' expression for changes 
      return scope.$eval(attrs.compile); 
      }, 
      function(value) { 
      // when the 'compile' expression changes 
      // assign it into the current DOM 
      element.html(value); 

      // compile the new DOM and link it to the current 
      // scope. 
      // NOTE: we only compile .childNodes so that 
      // we don't get into infinite loop compiling ourselves 
      $compile(element.contents())(scope); 
      } 
     ); 
     }; 
    }) 

2. Controller 
    ---------- 

    app.controller("TaskDetailCtrl", function ($scope, $state, $stateParams, $sce, $compile) { 

     cur_task = $stateParams.newTask; 
     $scope.title = cur_task.title; 
     $scope.showTask = "<" + cur_task.type + "taskdirective" + "></" + cur_task.type + "taskdirective" + ">"; 

    }); 

3. HTML 

<div compile="showTask"></div> 
+0

非常感謝你,那定了! 所以也許更好的解決方案是使用stateProvider來執行不同的任務,而不是隻使用一個具有不同指令的任務狀態...... –