1

I want to try:

function test(){
   $('#somediv').html('<div ng-model="name">{{name}}</div>');
}

Is there any way to do this?

1
  • jQueryish DOM manipulation isn't a good practice with Angular. You can use ng-show/hide and ng-if for this purpose instead Commented Apr 25, 2017 at 7:46

3 Answers 3

1

When you add html which contains angular's built-in directives, you have to recompile it by $compile in order to let angular recognize.

refer the below code snippet.

angular.module("app", [])
  .controller("myCtrl", function($scope, $compile) {
    $scope.name = 'test value';
    $scope.test = function() {
      var element = angular.element($('#somediv'));
      element.html('<div ng-model="name">{{name}}</div>');
      $compile(element)($scope);
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="app" ng-controller="myCtrl">
  <input type="text" ng-model="name">
  <button ng-click="test()">Add</button>
  <div id="somediv"></div>
</div>

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

Comments

0

You need to use $compile service.

Just compile the html string like:

var html = $compile('<div ng-model="name">{{name}}</div>')($scope);

Don't forget to inject the $compile service into your controller.

2 Comments

Thank Hasan Ibrahim, I tried to do the same idea in my angular controller, but something went wrong :( stackoverflow.com/questions/43603948/…
@NhạHoàng accept this one as well. Because this is the way to go :)
0

Don't use jQuery DOM Manipulation in Angular, instead do something like:

angular.module("main", []).controller("mainController", function($scope){

  $scope.toggle = function(){
  
    $scope.show = !$scope.show;
  
  }

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<html ng-app="main"> 
<head> </head>


<body ng-controller="mainController">
<div>
<button ng-click="toggle()"> Toggle Div </button>


<div ng-if="show"> Div Contents </div>
</div>
</body>
</html>

Comments

Your Answer

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