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

1

In the angular, I realize that the scope of the Controller is not being applied in a certain part of the code, when it is created dynamically.

For example, I have a certain content inside a script tag, with type set to text/ng-template , so I can use it as a template. I want to add this excerpt to an existing Controller. But while doing this, the angle is not being processed in the new html generated.

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><scriptsrc="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 make the excerpt added in the controller interpreted by AngularJS ?

    
asked by anonymous 04.08.2016 / 18:23

1 answer

2

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

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><scriptsrc="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>
    
04.08.2016 / 18:31