javascript - 使用 js bookmarklet 制作一个 Angular 应用程序

标签 javascript angularjs bookmarklet

我正在尝试通过单击 JS 书签从站点中创建一个 angularjs 应用程序。

问题是 ng-controller 不能被 angular 识别并抛出这个错误:

Error: Argument 'LDController' is not a function, got undefined

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

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

function loadApp() {
  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);
}

(function () {
  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);
  }
  else {
    loadApp();
  }
}());

最佳答案

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

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

还有更多信息here

关于javascript - 使用 js bookmarklet 制作一个 Angular 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16691750/

相关文章:

javascript - 无法更改 body 元素的 html

Javascript 书签在 Firefox 中输出 'true' 而不是执行脚本

javascript - 从原始数据制作 WAV 文件

javascript - Xpathresult 在 IE11 中未定义

javascript - 如何在mysql查询中精确找到选定对 Angular 线区域之间的数据

javascript - 在 AngularJS 中调用 jQuery 函数

javascript - AngularJS 多次处理调用 promise

javascript - 为什么这个简单的谷歌地图代码不起作用?

javascript - 无法使用 vm 绑定(bind)到范围。 controller/html 中的符号

javascript - 我如何使用 javascript 获取页面上包含特定单词的链接