2016-07-06 24 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来执行不同的任务,而不是只使用一个具有不同指令的任务状态...... –