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?

5
  • Do you mean something like ngInclude? Commented Mar 29, 2015 at 21:38
  • I mean when I get data from socket.io I wanna to insert data in exists div Commented Mar 29, 2015 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. docs.angularjs.org/api/ng/function/angular.element Commented Mar 29, 2015 at 21:58
  • stackoverflow.com/questions/18690804/… Commented Mar 29, 2015 at 22:14
  • But id I want change variable angulars by Jquery, is possible? Commented Mar 29, 2015 at 22:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.