在将一些 html 附加到 DOM 后初始化 AngularJS 控制器 [英] Initialize AngularJS controller after append some html into DOM

查看:19
本文介绍了在将一些 html 附加到 DOM 后初始化 AngularJS 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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/

我想我需要使用 $compile 但在没有任何作用域的地方使用.

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}]');

推荐答案

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

说明:

angular.bootstrap(rootElementForApp, arrayOfModulesForTheApp)

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

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.

所以我们所做的与:

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

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

这篇关于在将一些 html 附加到 DOM 后初始化 AngularJS 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆