David Slavík
David Slavík

Reputation: 1192

Initialize AngularJS controller after append some html into DOM

Is there a way how to use $compile from pure javascript? I'm combinating basic javascript and places where I'm using Angular and can't find a way how to do something like this: http://jsfiddle.net/DavidSlavik/bFdcJ/1/

I think I need use $compile but from place where is no any scope.

angular.module('myApp', []);

function ExpensesCtrl($scope) {

    // Here are some master functions...    

}    


$(function () {

   // Here is the Ajax function that returns html from my MVC action processed with Razor
   // Here I'm not using AngularJS and scopes...
   var htmlFromAjax = '<div id="mapOrder" ng-controller="sortable"><div ng-repeat="item in SortItems">{{item.Title}}</div></div>';
   $('body').append(htmlFromAjax);

});

function sortable($scope, $http, $element) {

    // Here is the Ajax function that return JSON object. For example it is commented and used static variable SortItems in scope.
    //$http.get('someUrlWitchReturnsJsonObject')
    //    .success(function (e) {
    //        $scope.SortItems = e;
    //    });

    $scope.SortItems = JSON.parse('[{"Title":"ddddddd","MapId":5,"Order":0},{"Title":"Moje mapa","MapId":3,"Order":2},{"Title":"asdas","MapId":4,"Order":3},{"Title":"asds","MapId":7,"Order":4},{"Title":"Pokus","MapId":8,"Order":5},{"Title":"Hello world!!!","MapId":1,"Order":10}]');

Upvotes: 6

Views: 5088

Answers (2)

Umur Kontacı
Umur Kontacı

Reputation: 35478

angular.bootstrap($("#targetElmForApp")[0], ["myApp"]);

Explanation:

angular.bootstrap(rootElementForApp, arrayOfModulesForTheApp)

The first parameter sets the root element for the app, which is what you would do by using ng-app directive otherwise.

The second parameters is a list of modules that defines the application. This is typically a single module in which the app is defined.

So what we did is the same as:

<div id="targetElmForApp" ng-app="myApp"></div>

see:
http://docs.angularjs.org/api/angular.bootstrap
http://docs.angularjs.org/guide/bootstrap

Upvotes: 9

David Slav&#237;k
David Slav&#237;k

Reputation: 1192

Alternative way from this post: AngularJS + JQuery : How to get dynamic content working in angularjs

        angular.element(document).injector().invoke(function ($compile) {
                var container = $('#some-dom-element');
                var scope = angular.element(container).scope();
                $compile(container)(scope);
        });

Upvotes: 0

Related Questions