1

What easy way to insert html item to exists template HTML in angularjs? For example there is template generated in PHP:

<div id="block">
<!-- Insert here template from Angularjs-->
<div class="item"></div>
<div class="item"></div>
</div>

I can Use Jquery like as:

$('#block').prepend('<div class="item"></div>');

How I can same in Angularjs?

Sahe
  • 163
  • 4
  • 14
  • Do you mean something like [ngInclude](https://docs.angularjs.org/api/ng/directive/ngInclude)? – Ilya Luzyanin Mar 29 '15 at 21:38
  • I mean when I get data from socket.io I wanna to insert data in exists `div` – Sahe Mar 29 '15 at 21:51
  • angular.element has both prepend and append methods just like jquery. It's doubtful if they should be used but they certainly can be. https://docs.angularjs.org/api/ng/function/angular.element – Cerad Mar 29 '15 at 21:58
  • http://stackoverflow.com/questions/18690804/insert-and-parse-html-into-view-using-angularjs – Newtt Mar 29 '15 at 22:14
  • But id I want change variable angulars by Jquery, is possible? – Sahe Mar 29 '15 at 22:25

2 Answers2

0

You can use jquery to add HTML but you'll need to compile it first using

var compiledHTML = $compile(html)($scope);

and then pass it on to jquery's method

$('#block').prepend(compiledHTML);

But as @cerad mentioned definitely this is not the best way.

Nikhil Bhandari
  • 1,584
  • 2
  • 16
  • 34
0

You should use angular's data binding, you can also treat is as a template engine.

eg:

your html code is this

<ul>
  <li ng-repeat="msg in allMsgs">{{msg}}</li>
</ul>

your controller code is this

app.controller($scope){
   $scope.allMsgs = [];

   // i dont know socket.io well, so this part may not work :)
   // and it's better to separate it to a service and use $rootScope.$apply()
   soceket.on('msg',function(msg){
     $scope.$apply(function(){
        $scope.allMsgs.push(msg);
     });
   });
}

Note you need to use $apply in order to make the data binding work when data is changed by events that angular doesn't control.

Some useful links

at15
  • 139
  • 6