angularjs – 注入动态html似乎没有编译

前端之家收集整理的这篇文章主要介绍了angularjs – 注入动态html似乎没有编译前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用angularJS解决一个主要问题,即使用包含ng-controller的动态添加的html.

让我们说我想在DOM中添加一个div作为ng-controller,它将绑定的数据脱离显示.我可以成功实现如下:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script>
        var demoData = {
            'test1': 'one','test2': 'two'
        };

        var myApp = angular.module('myApp',[]);
        myApp.controller('TestCtrl',function ($scope) {
            $scope.demo = demoData;
        });
    </script>
</head>
<body>
    <div ng-controller="TestCtrl">
        {{demo}}
    </div>            
</body>
</html>

按预期输出以下内容

{“test1″:”one”,”test2″:”two”}

但是,现在可以说div实际上必须动态加载,也许当用户按下按钮时.在这种情况下,我将使用以下内容替换上例中的标记

<body>
    <button onclick="addDiv();">Click to add Div!</button>
    <script>
        function addDiv() {
            var newDiv = $('<div ng-controller="TestCtrl">{{demo}}</div>');
            $(document.body).append(newDiv);
        }
    </script>
</body>

单击按钮时输出以下内容

Click to add Div!
{{demo}}

到目前为止,这是有道理的; angular已经在DOM中完成了它的工作,完成了它.它没有被告知有关新内容添加.
因此,如果我们查看AngularJS手册,就在this page底部,我们会发现如何告诉它我们刚刚添加了一些内容

Sometimes you want to get access to the injector of a currently
running Angular app from outside Angular. Perhaps,you want to inject
and compile some markup after the application has been bootstrapped.
You can do this using the extra injector() added to JQuery/jqLite
elements. See angular.element.

This is fairly rare but could be the case if a third party library is
injecting the markup.

In the following example a new block of HTML containing a
ng-controller directive is added to the end of the document body by
JQuery. We then compile and link it into the current AngularJS scope.
var $div = $(‘{{content.label}}’);
$(document.body).append($div);

06002

所以……考虑到这一点,我们在我们的示例中更新addDiv()函数,如下所示:

function addDiv() {
    var $newDiv = $('<div ng-controller="TestCtrl">{{demo}}</div>');
    $(document.body).append($newDiv);

    angular.element(document).injector().invoke(function ($compile) {
        var scope = angular.element($newDiv).scope();
        $compile($newDiv)(scope);
    });
}

现在,当我们运行它时,我们应该是金色的吗?
不,我们仍然得到以下内容

Click to add Div!
{{demo}}

sad panda is sad

你能指出我做错了什么,因为谷歌搜索和阅读手册没有结束,因为一切似乎都表明我的代码是正确的!

解决方法

从Angular ng-click调用函数调用时,您的代码将按原样运行.

由于您似乎真的想避免使用Angular,因此需要传统的onclick事件处理程序,因此需要将更改包装到$scope的调用中.$apply():http://plnkr.co/edit/EeuXf7fEJsbBmMRRMi5n?p=preview

angular.element(document).injector().invoke(function ($compile,$rootScope) {
    $rootScope.$apply(function() {
        var scope = angular.element($newDiv).scope();
        $compile($newDiv)(scope);
    });
});

猜你在找的Angularjs相关文章