javascript - How to re-render directive with new template in Angularjs? -
i'm doing simple web project, got issue angular directive. can not re-render html, render @ first time. code: http://plnkr.co/edit/jc9wnomrmlwabrdsoviu?p=preview
app.directive('dytemplate', ['$compile',function($compile) { var gettemplate = function(contenttype) { templatemap = { 1: '<div><a href="" ng-click="changetemplate(2)"> alter template 2</a></div>', 2: '<div><a href="" ng-click="changetemplate(3)"> alter template 3</a></div>', 3: '<div><a href="" ng-click="changetemplate(1)"> alter template 1</a></div>' }; homecoming templatemap[contenttype]; } homecoming { restrict: 'ea', link: function(scope, element, attrs) { // default load template element.html(gettemplate(1)); element.replacewith($compile(element.html())(scope)); scope.changetemplate = function(templateid) { element.html(gettemplate(templateid)); element.replacewith($compile(element.html())(scope)); } } } } ]);
you're using element.replacewith()
, first time removes element dom, later calls doesn't alter dom, since element
isn't in more.
i suspect you're overcomplicating things using $compile
. in situations it's improve (because it's simpler) utilize template
alternative in directive. angular handles compilation you. in template, can utilize {{}}
interpolation, phone call functions, , alter what's beingness displayed using ngif
if need to, compiled template, , there isn't need manually compiling or tinkering dom.
an illustration of can seen @ http://plnkr.co/edit/17empwulkfr904qti2oe?p=preview
var app = angular.module('myapp',[]); app.directive('dytemplate', function() { homecoming { restrict: 'ea', scope:{}, template: '<div><a href="" ng-click="shownexttemplate()"> alter template {{nexttemplateid()}}</a></div>', link: function(scope, element, attrs) { scope.templateid = 1; scope.nexttemplateid = function() { var templatemap = { 1: 2, 2: 3, 3: 1 }; homecoming templatemap[scope.templateid]; }; scope.shownexttemplate = function() { scope.templateid = scope.nexttemplateid(); }; } }; });
javascript angularjs
No comments:
Post a Comment