How to apply a scope to a dynamically created element in Angularjs?

Asked

Viewed 76 times

1

At the angle, I realize that the scope of the Controller is not being applied in a particular piece of code, when it is created dynamically.

For example, I have a certain content within a tag script, with the type defined to text/ng-template, to use as a template. I want to add this snippet to an existing Controller. But in doing so, the angular is not being processed in the new generated html.

Example:

angular.module('app', [])

.controller('TestCtrl', function ($scope)
{
     $scope.name = 'Wallace';
  
  $('#ctrl').append($('#tpl-name').html());

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
   <div ng-controller="TestCtrl" id="ctrl">
       <p>Meu nome é {{  name }}</p>
   </div>
</div>

<script type="text/ng-template" id="tpl-name">
  <b>Meu nome é {{ name }}</b>
</script>

How can I get the chunk added to the controller to be interpreted by AngularJS?

1 answer

2


You must compile your template, specifying the scope of the compilation. This is done through the service $compile.

angular.module('app', []).controller('TestCtrl', function ($scope, $compile) {
    $scope.name = 'Wallace';
    $('#ctrl').append($compile($('#tpl-name').html())($scope));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
   <div ng-controller="TestCtrl" id="ctrl">
       <p>Meu nome é {{  name }}</p>
   </div>
</div>

<script type="text/ng-template" id="tpl-name">
  <b>Meu nome é {{ name }}</b>
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.