2

I was performing a demo of angularjs example at Jsfiddle. I am simply creating a angularjs directive, which will display a div with background-color red, with static text containing data-bindings as template.

var objApp = angular.module("myApp", []);
objApp.controller("myAppController", 
    function($scope) {
       $scope.name2="temp";
    });

objApp.directive("myAppDirective",
    function(){
        return {
           template : "<div style='background-color:red'>"+
                           "Hello {{name}}"+
                           "<div ng-transclude></div>"+
                      "</div>",
           scope : true,
           transclude : true,
           controller : function($scope) {
               $scope.name = "tempController";
           },
           compile : function(tElem, attrs, transcludeFn) {
               return function(scope, iElem, attrs, transcludeFn) {
                   console.log(iElem.html());
                   //iElem.html("<div ng-show='false'>" + 
                   //                  iElem.html() + 
                   //            "</div>");
               }
           }
  });

When following line is commented, every binding works fine.

iElem.html("<div ng-show='false'>" + iElem.html() + "</div>")

But as soon as comment is removed, binding gets broken. Why is it happening ? Does I have to use $compile on new html, which I am setting on iElem ? Does it was already compiled, when this line was commented ? I have looked for answers, but none of them helped me out.

Jon B
  • 51,025
  • 31
  • 133
  • 161
Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97

1 Answers1

0

Yes. You need to use $compile as follows

$compile('<div ng-show="false">'+iElem.html()+'</div>')($scope, function(cloned, scope){
                elem.append(cloned); 
});

EDIT: Seems your problem is similar to this post. Check it out here

Community
  • 1
  • 1
Partha Sarathi Ghosh
  • 10,936
  • 20
  • 59
  • 84
  • Can you let me know why $compile() is required in link function ? While if I use compile() function in directive, then things works fine, why is it so ? Can you give me a detailed explanation regarding when to use compile ? – Mangu Singh Rajpurohit Dec 18 '15 at 01:39