Angular bootstrapping after load of html

后端 未结 4 394
不知归路
不知归路 2020-12-31 08:45

I first initialize my app with ng-app=\"myApp\" in the body tag and this works fine for all angularized-html that is loaded on first page load.

Later on I have some

4条回答
  •  悲哀的现实
    2020-12-31 09:33

    I will echo what others have mentioned: this kind of thing is generally a bad idea, but I also understand that you sometimes have to work with legacy code in ways you'd prefer not to. All that said, you can turn HTML loaded from outside Angular into Angular-bound views with the $compile service. Here's how you might rewrite your current example to make it work with $compile:

    // We have to set up controllers ahead of time.
    myApp.controller('AfterCtrl', function($scope)  {
      $scope.loaded = 'Is now loaded';
    });
    
    //loads html and afterwards creates a controller
    $('button').on('click', function() {
      $.get('ajax.html', function(data) {
    
        // Get the $compile service from the app's injector
        var injector = $('[ng-app]').injector();
        var $compile = injector.get('$compile');
    
        // Compile the HTML into a linking function...
        var linkFn = $compile(data);
        // ...and link it to the scope we're interested in.
        // Here we'll use the $rootScope.
        var $rootScope = injector.get('$rootScope');
        var elem = linkFn($rootScope);
        $('.content').append(elem);
    
        // Now that the content has been compiled, linked,
        // and added to the DOM, we must trigger a digest cycle
        // on the scope we used in order to update bindings.
        $rootScope.$digest();
    
      }, 'html');
    });
    

    Here is an example: http://plnkr.co/edit/mfuyRJFfA2CjIQBW4ikB?p=preview

    It simplifies things a bit if you can build your functionality as a directive instead of using raw jQuery--you can inject the $compile and $rootScope services into it, or even use the local scope inside the directive. Even better if you can use dynamic binding into an element instead.

提交回复
热议问题