angularjs - angular directive doesnt render the template, after adding html dynamically in controller -
my problem directive doesnt show template. added html tag specific name in controller dom via "$sce.trustashtml(taskdirective)" , "$compile(taskdirective)($scope)". controller-function inside directive called. template not showing up.
im using $stateprovider, calls "taskdetailctrl" html.
anybody can help?
thank you!+
controller:
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); });
directive:
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 showing up!") } } });
html:
<div ng-bind-html="showtask"></div>
$sce.trustashtml , ng-bind-html not meant build html directives. technique not work.
this because angular works first compiling , linking. see conceptual overview explaination.
in short, time link html defined in trustashtml, late angular compile (and therefore understand) directive.
in order dynamically add html, should looking @ $compile service (and/or directives). docs here.
although adding solution problem below:
1. make below directive compile , append directive element specified it. app.directive('compile', function($compile) { // directive factory creates link function return function(scope, element, attrs) { scope.$watch( function(scope) { // watch 'compile' expression changes return scope.$eval(attrs.compile); }, function(value) { // when 'compile' expression changes // assign current dom element.html(value); // compile new dom , link current // scope. // note: compile .childnodes // don't 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>
Comments
Post a Comment