How to bind an AngularJS controller to dynamically added HTML?

后端 未结 6 620
清歌不尽
清歌不尽 2020-12-03 02:13

For this scenario, I have a page of HTML with some AngularJS directives, controllers, etc.

Something like this:



  
6条回答
  •  悲&欢浪女
    2020-12-03 02:28

    Lets take a small template

     var  template = '
    '; template += ''; template += '
    ';

    Now if you want to add this template you have to do the following two things:

    1) Instantiate your controller by $controller

    2) Compile your template.

    //this creates a new scope
    var $scope = $rootScope.$new();  
    //Controller initialize with $scope
    $controller('someController',{$scope,$scope});   
    var templateEl = angular.element(template);
    //Now compile the template with scope $scope
    $compile(templateEl)($scope);
    angular.element('body').append(templateEL);
    

提交回复
热议问题