How to bind an AngularJS controller to dynamically added HTML?

后端 未结 6 621
清歌不尽
清歌不尽 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:21

    I've faced the same issue, here's what I came up with :

    2nd controller's view should be rendred here

    and calling setCnt() function will inject and compile the html, and it will be linked to the 2nd controller:

    var app = angular.module('app', []);
    
    function setCnt() {
      // Injecting the view's html
      var e1 = angular.element(document.getElementById("ee"));
      e1.html('
    my name: {{name}}
    '); // Compile controller 2 html var mController = angular.element(document.getElementById("mController")); mController.scope().activateView(e1); } app.controller("mainController", function($scope, $compile) { $scope.name = "this is name 1"; $scope.activateView = function(ele) { $compile(ele.contents())($scope); $scope.$apply(); }; }); app.controller("ctl2", function($scope) { $scope.name = "this is name 2"; });

    here's an example to test this : https://snippet.run/x4bc

    hope this helps.

提交回复
热议问题