2

可能这是一个微不足道的问题,但对于 AngularJS 新手来说,这是一个问题^_^

我最初想要实现的是使用 ng-click 指令使动态插入的标签(通过 jQuery)工作。我搜索并发现我必须获得AngularJS Injector,然后编译该代码。所以这是最简单的注入器代码形式,它对我不起作用,它有什么问题?

注意#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/

4

1 回答 1

3

ng模块_

  • angular.bootstrap使用时自动将ng模块添加到依赖项中(手动或使用ngApp
  • $rootScope/ $compileservices 是ng模块的一部分。
  • injector.invoke如果你想要这些服务,你需要使用。
  • 您可能应该以更传统的方式使用角度。

尝试这个:

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);

}]);
于 2014-02-11T07:58:23.000 回答