Jquery 动态加载单元角度范围的获取方法

Jquery 动态加载单元角度范围的获取方法,jquery,angularjs,Jquery,Angularjs,Angular不会编译直接放入DOM的html内容。为了让它进入进程指令,例如ng controller,您需要显式编译它。像这样的方法应该会奏效: $http.post('/SomeController/MyPartialAction', { data: "value" }).success(function (response) { //load the partial view HTML in the div $("#MyDiv").html(res

Angular不会编译直接放入DOM的html内容。为了让它进入进程指令,例如
ng controller
,您需要显式编译它。像这样的方法应该会奏效:

$http.post('/SomeController/MyPartialAction', { data: "value" }).success(function (response) {
//load the partial view HTML in the div
$("#MyDiv").html(response);        
});
或者您可以使用
ng include

newScope = $scope.$new();     // for a new child scope
newScope = $scope.$new(true); // for a new isolate scope
newScope = $scope;            // for an existing scope

$compile(insertedDomElement)(newScope);

$scope.template='您需要编译元素,以便将其附加到当前范围

为此,将服务注入控制器

将HTML字符串或DOM编译为模板并生成模板函数,然后可以使用该函数将作用域和模板链接在一起

在ajax之后编译并附加html,如

angularModule.controller("SomeController", ["$scope", "$http", "$compile", function  ($scope, $http, $compile) {
    $scope.someFunction = function myfunction() {

    }    
}]);
更新

如果您确实不能使用
$routes
来实现这一点,那么您可以这样做,但最好的方法是使用
$routes

#MyDiv
包装在一个div中,并为该div分配一个
控制器
,就像我已经将
ParentCtrl

$http.post('/SomeController/MyPartialAction', {data:"value"}).success(function(response) {
    //compile against the $scope here,
    var compiledElm = $compile(response)($scope);
    $("#MyDiv").html(compiledElm);        
});

下面是一个

如何使用ajax加载它?获取html作为字符串,并将其放入html?@K.Toress是的,div处于加载了ajax调用的局部视图中。请显示附加html内容的方式?@K.Toress我正在mvc项目中执行此操作。部分视图内容是通过一个div中的ajax加载的。请为ajax添加代码并将内容附加到html中?我使用了这个编译,但是当使用编译时,任何控制器都被定义到html中,需要首先定义。
这是您使用
ajax
加载的内容吗?是的,加载的内容定义了一个控制器。哦,我认为最好使用
$routes
然后我使用了这个编译,但是当使用编译时,任何控制器都被定义到HTML中,需要首先定义
angularModule.controller("SomeController", ["$scope", "$http", "$compile", function  ($scope, $http, $compile) {
    $scope.someFunction = function myfunction() {

    }    
}]);
$http.post('/SomeController/MyPartialAction', {data:"value"}).success(function(response) {
    //compile against the $scope here,
    var compiledElm = $compile(response)($scope);
    $("#MyDiv").html(compiledElm);        
});
<div ng-controller="ParentCtrl">
    <button ng-click="getHtml()">attach html</button>
    <div id="MyDiv"></div>
</div>
app.controller('ParentCtrl', function($scope, $timeout, $compile) {
    $scope.getHtml = function() {
        $timeout(function() {
            var html = '<div id="Some-div" data-ng-controller="SomeController">{{ name }}</div>';
            var compiled = $compile(html)($scope);
            $("#MyDiv").html(compiled);
        }, 1000);
     };
}