让我们说我想在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}}
解决方法
由于您似乎真的想避免使用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); }); });