[英]Angularjs: How To Inject Controller Into Module After DOM Is Initialized?
我正在使用控制器注入新的DOM:
app.controller('cart', function ($scope, $http) {
$scope.content = {
label: "hello, world!",
};
});
var $html = '<div ng-controller="cart"></div>';
var $root = $('[ng-app]');
angular.element($root).injector().invoke(function ($compile) {
var $scope = angular.element($root).scope();
$root.append($compile($html)($scope));
// Finally, refresh the watch expressions in the new element
$scope.$apply();
});
在$root.append($compile($html)($scope));
错误发生。 使用Chrome调试控制器时,甚至可以看到该控制器已在app
上注册。
代码有什么问题?
所以,如果我这样说:
var app = angular.module('app', ['ngSanitize']);
app.controller('base', function ($scope, $http) {
....
});
app.controller('cart', function ($scope, $http) {
....
});
在同一个文件中,它可以工作。 我的情况是我有2个独立的js文件。 一个文件包含:
var app = angular.module('app', ['ngSanitize']);
app.controller('base', function ($scope, $http) {
....
});
上面的文件首先被加载。 然后,第二个文件具有:
app.controller('cart', function ($scope, $http) {
....
});
var $html = '<div ng-controller="cart"></div>';
var $root = $('[ng-app]');
angular.element($root).injector().invoke(function ($compile) {
var $scope = angular.element($root).scope();
$root.append($compile($html)($scope));
// Finally, refresh the watch expressions in the new element
$scope.$apply();
});
并在第一个文件完成后加载。 因此,问题应更改为:
模块初始化后如何向模块注入新的控制器?
我在互联网上找到的。 它显示了在引导Angularjs之后如何注入控制器,指令,过滤器等。 分配模块后,调用app.config()
。
var app = angular.module('app', ['ngSanitize']);
app.config(
function( $controllerProvider, $provide, $compileProvider ) {
// Since the "shorthand" methods for component
// definitions are no longer valid, we can just
// override them to use the providers for post-
// bootstrap loading.
console.log( "Config method executed." );
// Let's keep the older references.
app._controller = app.controller;
app._service = app.service;
app._factory = app.factory;
app._value = app.value;
app._directive = app.directive;
// Provider-based controller.
app.controller = function( name, constructor ) {
$controllerProvider.register( name, constructor );
return( this );
};
// Provider-based service.
app.service = function( name, constructor ) {
$provide.service( name, constructor );
return( this );
};
// Provider-based factory.
app.factory = function( name, factory ) {
$provide.factory( name, factory );
return( this );
};
// Provider-based value.
app.value = function( name, value ) {
$provide.value( name, value );
return( this );
};
// Provider-based directive.
app.directive = function( name, factory ) {
$compileProvider.directive( name, factory );
return( this );
};
// NOTE: You can do the same thing with the "filter"
// and the "$filterProvider"; but, I don't really use
// custom filters.
}
);
然后执行app.controller('base', function ($scope, $http) { ....
或定义过滤器/指令/等。
这是Ben Nadel的链接 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.