6

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}]');
David Slavík
  • 1,132
  • 1
  • 14
  • 23

2 Answers2

9
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

JFK
  • 40,963
  • 31
  • 133
  • 306
Umur Kontacı
  • 35,403
  • 8
  • 73
  • 96
0

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);
        });
Community
  • 1
  • 1
David Slavík
  • 1,132
  • 1
  • 14
  • 23