在将一些html附加到DOM后初始化AngularJS控制器

Dav*_*vík 6 angularjs

有没有办法如何从纯JavaScript使用$ compile?我正在组合基本的javascript和我正在使用Angular的地方,并且找不到如何做这样的事情的方法:http://jsfiddle.net/DavidSlavik/bFdcJ/1/

我想我需要使用$ compile但是从没有任何范围的地方.

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}]');
Run Code Online (Sandbox Code Playgroud)

Umu*_*acı 9

angular.bootstrap($("#targetElmForApp")[0], ["myApp"]);
Run Code Online (Sandbox Code Playgroud)

说明:

angular.bootstrap(rootElementForApp, arrayOfModulesForTheApp)
Run Code Online (Sandbox Code Playgroud)

第一个参数设置应用程序的根元素,ng-app否则您将使用指令执行此操作.

第二个参数是定义应用程序的模块列表.这通常是定义应用程序的单个模块.

所以我们做的是:

<div id="targetElmForApp" ng-app="myApp"></div>
Run Code Online (Sandbox Code Playgroud)

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

  • 救了我的命!Tesekkurler dostum!:) (2认同)