4

我正在尝试通过单击 JS 小书签从网站制作 angularjs 应用程序。

问题是 ng-controller 无法被 angular 识别并抛出此错误:

错误:参数“LDController”不是函数,未定义

首先我定义 ng-app 并使用 angular.module 具有相同的名称,这有效,我得到了<html ng-app="bookmarklet">。然后我加载一个名为 application.js 的外部文件。app.controller('LDController', ..)在这个文件中定义!

我做错了什么?这是 js 小书签代码:

函数加载应用程序(){
  document.getElementsByTagName('html')[0].setAttribute('ng-app', 'bookmarklet');

  var div = document.createElement('div');
  div.setAttribute('ng-controller', 'LDController');
  div.innerHTML = '';
  document.body.appendChild(div);

  var js = document.createElement('script');
  js.innerText = "var app = angular.module('bookmarklet', []);";
  document.body.appendChild(js);

  js = document.createElement('script');
  js.setAttribute('src', 'http://example.org/js/application.js');
  document.body.appendChild(js);
}

(功能 () {
  if (typeof angular === 'undefined') {
    js = document.createElement('script');
    js.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/angularjs/1.1.4/angular.min.js');
    js.onload = loadApp;
    document.body.appendChild(js);
  }
  别的 {
    加载应用程序();
  }
}());
4

2 回答 2

3

我一直在想,您正在通过添加ng-app指令手动初始化 Angular。执行此操作的规定方法是不插入,而是在设置其他所有内容后ng-app调用适当的元素。angular.bootstrap例如:

angular.element(document).ready(function() {
    angular.bootstrap(document, ['bookmarklet']);
}

这里有更多信息

于 2013-05-23T14:40:07.437 回答
2

所以我已经解决了,感谢Ram Rajamony

这是作为要点的解决方案:https ://gist.github.com/lpsBetty/5636338

于 2013-05-23T14:15:26.943 回答