相关疑难解决方法(0)

动态加载AngularJS控制器

我有一个现有的页面,我需要删除一个带有可以动态加载的控制器的角度应用程序.

这是一个片段,它根据API和我发现的一些相关问题实现了我应该如何完成的最佳猜测:

// Make module Foo
angular.module('Foo', []);
// Bootstrap Foo
var injector = angular.bootstrap($('body'), ['Foo']);
// Make controller Ctrl in module Foo
angular.module('Foo').controller('Ctrl', function() { });
// Load an element that uses controller Ctrl
var ctrl = $('<div ng-controller="Ctrl">').appendTo('body');
// compile the new element
injector.invoke(function($compile, $rootScope) {
    // the linker here throws the exception
    $compile(ctrl)($rootScope);
});
Run Code Online (Sandbox Code Playgroud)

JSFiddle.请注意,这是实际事件链的简化,上面的行之间有各种异步调用和用户输入.

当我尝试运行上面的代码时,$ compile返回的链接器抛出:Argument 'Ctrl' is not a function, got undefined.如果我正确理解了引导程序,它返回的注入器应该知道Foo模块,对吧?

相反,如果我使用一个新的注入器angular.injector(['ng', 'Foo']),它似乎工作,但它创建一个新的$rootScope,不再与Foo模块被引导的元素相同的范围. …

javascript angularjs

64
推荐指数
3
解决办法
8万
查看次数

仅在需要时动态注入模块

我正在将Require.js与Angular.js结合使用.

某些控制器需要巨大的外部依赖性,而其他控制器则不需要,例如,FirstController需要Angular UI Codemirror.这是额外的135 kb,至少:

require([
  "angular",
  "angular.ui.codemirror" // requires codemirror itself
], function(angular) {
  angular.module("app", [ ..., "ui.codemirror" ]).controller("FirstController", [ ... ]);
});
Run Code Online (Sandbox Code Playgroud)

每次我的页面加载时我都不想要包含指令和Codemirror lib,只是为了让Angular满意.
这就是为什么我现在只在路线被击中时加载控制器,就像这里所做的那样.

但是,当我需要类似的东西时

define([
  "app",
  "angular.ui.codemirror"
], function(app) {
  // ui-codemirror directive MUST be available to the view of this controller as of now
  app.lazy.controller("FirstController", [
    "$scope",
    function($scope) {
      // ...
    }
  ]);
});
Run Code Online (Sandbox Code Playgroud)

如何告诉Angular ui.codemirror在app模块中注入模块(或任何其他模块)?
我不在乎它是否是一种完成此操作的hackish方式,除非它涉及修改外部依赖项的代码.

如果它有用:我正在运行Angular 1.2.0.

requirejs angularjs

44
推荐指数
2
解决办法
6万
查看次数

当您只能访问模块变量时注入模块

假设你有一个

var app = angular.module('Mod1',[])
Run Code Online (Sandbox Code Playgroud)

现在你需要向该模块注入其他东西,但你不能改变那一行,你只能访问该app变量.

所以这不起作用吧?

var mod2 = angular.module('mod2',[]).factory('$myService', function(){ 
       return { do: function(){alert('doing'); }
})

app.directive('foo',[$myService]) // $myService here is undefined
Run Code Online (Sandbox Code Playgroud)

你当然可以做到:

injector = angular.injector(['mod2'])
$myService = injector.get('$myService')
Run Code Online (Sandbox Code Playgroud)

虽然我想知道是否有更优雅的解决方案

angularjs

4
推荐指数
1
解决办法
5765
查看次数

标签 统计

angularjs ×3

javascript ×1

requirejs ×1