May be it's trivial question, but for AngularJS newbie it's a matter ^_^
可能这是微不足道的问题,但对于AngularJS新手的问题^ _ ^
What I'm trying to originally achieve is to make a dynamically inserted tag (by jQuery) with ng-click directive to work. I've searched and found that I've to get AngularJS Injector, then compile that code. So here it is the simplest form of the injector code which is NOT working for me, what's wrong with it?
我最初想要实现的是用ng-click指令动态地插入标签(jQuery)。我搜索了一下,发现我必须得到AngularJS注入器,然后编译代码。这是喷射器代码最简单的形式它对我不起作用,有什么问题吗?
Note #1: The dynamically inserted tag with ngDirective is done outside AngularJS scope.
注意#1:带有ngDirective的动态插入标签是在AngularJS作用域之外完成的。
angular.module('simpleExample', [])
.run(
[ '$rootScope',
function ($rootScope) {
$rootScope.test = "Test";
}]);
console.log(angular.injector(['simpleExample']));
// console.log(angular.injector(['simpleExample']).$compile('<a href="" ng-click="someFunctionOnRootScope()">Text</a>'));
http://jsfiddle.net/Zx8hr/6/
1 个解决方案
#1
3
The ng
module
-
angular.bootstrap
automatically adds theng
module to the dependencies when used (manually or withngApp
) - 角。引导程序在使用时自动将ng模块添加到依赖项中(手动或使用ngApp)
-
$rootScope
/$compile
services are part of theng
module. - $rootScope / $compile服务是ng模块的一部分。
- You need to use
injector.invoke
if you want these services. - 你需要使用喷射器。如果需要这些服务,请调用它们。
- You should probably use angular in more traditional ways.
- 你可能应该用更传统的角度。
Try this:
angular.module('simpleExample', ['ng']);
angular.injector(['simpleExample'])
.invoke(['$rootScope','$compile',
function($rootScope, $compile){
var elm = $compile('<a href="" ng-click="someFunctionOnRootScope()">Text</a>')($rootScope);
$rootScope.someFunctionOnRootScope = function(){
alert("Hello there!");
}
angular.element(document.body).append(elm);
}]);
#1
3
The ng
module
-
angular.bootstrap
automatically adds theng
module to the dependencies when used (manually or withngApp
) - 角。引导程序在使用时自动将ng模块添加到依赖项中(手动或使用ngApp)
-
$rootScope
/$compile
services are part of theng
module. - $rootScope / $compile服务是ng模块的一部分。
- You need to use
injector.invoke
if you want these services. - 你需要使用喷射器。如果需要这些服务,请调用它们。
- You should probably use angular in more traditional ways.
- 你可能应该用更传统的角度。
Try this:
angular.module('simpleExample', ['ng']);
angular.injector(['simpleExample'])
.invoke(['$rootScope','$compile',
function($rootScope, $compile){
var elm = $compile('<a href="" ng-click="someFunctionOnRootScope()">Text</a>')($rootScope);
$rootScope.someFunctionOnRootScope = function(){
alert("Hello there!");
}
angular.element(document.body).append(elm);
}]);