我首先使用body标签中的ng-app ="myApp"初始化我的应用程序,这适用于首页加载时加载的所有angularized-html.
后来我有一些代码将angularized-html加载到DOM中.
在角度1.08中我可以在加载后运行angular.bootstrap($ newLoadHTML,["myApp"])并且它可以工作; $ newLoadHTML是用jQuery抓取的新添加的HTML.
在角度1.2这不再起作用:(
错误:[ng:btstrpd] App已经使用此元素进行了自助启动'' http://errors.angularjs.org/1.2.0-rc.2/ng/btstrpd?p0=%3Cdiv%20ng-controller%3D%22AfterCtrl% 22%3E
我收到了这个我理解的错误,但我不知道如何解决它.
我需要做的是加载angularized-html然后使角度意识到它.
这是一个说明它的插图:http://plnkr.co/edit/AHMkqEO4T6LxJvjuiMeT?p = preview
Mic*_*ley 15
我会回应别人提到的内容:这种事情通常是一个坏主意,但我也理解你有时必须以你不愿意的方式使用遗留代码.总而言之,您可以将从Angular外部加载的HTML转换为使用该$compile服务的 Angular-bound视图.以下是您可以重写当前示例以使其适用的方法$compile:
// We have to set up controllers ahead of time.
myApp.controller('AfterCtrl', function($scope) {
$scope.loaded = 'Is now loaded';
});
//loads html and afterwards creates a controller
$('button').on('click', function() {
$.get('ajax.html', function(data) {
// Get the $compile service from the app's injector
var injector = $('[ng-app]').injector();
var $compile = injector.get('$compile');
// Compile the HTML into a linking function...
var linkFn = $compile(data);
// ...and link it to the scope we're interested in.
// Here we'll use the $rootScope.
var $rootScope = injector.get('$rootScope');
var elem = linkFn($rootScope);
$('.content').append(elem);
// Now that the content has been compiled, linked,
// and added to the DOM, we must trigger a digest cycle
// on the scope we used in order to update bindings.
$rootScope.$digest();
}, 'html');
});
Run Code Online (Sandbox Code Playgroud)
这是一个例子:http://plnkr.co/edit/mfuyRJFfA2CjIQBW4ikB?p = preview
它简化了事情有点如果你可以建立自己的功能为指令,而不是使用原始的jQuery -你可以注入$compile和$rootScope服务融入它,甚至用伪指令中的局部范围.如果您可以将动态绑定用于<ng-include>元素,那就更好了.
这个问题的答案解决了我的问题。因为我需要在内容添加到 DOM 后创建控制器。此修复程序还要求我在声明控制器后注册控制器。如果有人有更简单的解决方案,请参与。
| 归档时间: |
|
| 查看次数: |
13800 次 |
| 最近记录: |