Reputation:
I want to try:
function test(){
$('#somediv').html('<div ng-model="name">{{name}}</div>');
}
Is there any way to do this?
Upvotes: 1
Views: 2035
Reputation: 209
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>
Upvotes: 0
Reputation: 38171
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>
Upvotes: 1
Reputation: 1898
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.
Upvotes: 0