Javascript 如何在angular';s控制器?

Javascript 如何在angular';s控制器?,javascript,html,angularjs,three.js,Javascript,Html,Angularjs,Three.js,我使用three.jsthreeDimView编写了一个类,其中包含我的场景、相机等。我在js代码中创建了这个类的全局对象threeDimView threeDimView_ = new threeDimView(); 现在我想在另一个div中显示一些与此相关的信息 如何将此对象-threeDimView\uz放入此信息分区的控制器中 function infoController(threeDimView_, $scope) 如果我将其与$scope一起传递给控制器,我会得到一个错误:

我使用three.js
threeDimView
编写了一个类,其中包含我的场景、相机等。我在js代码中创建了这个类的全局对象
threeDimView

threeDimView_ = new threeDimView();
现在我想在另一个div中显示一些与此相关的信息

如何将此对象-
threeDimView\uz
放入此信息分区的控制器中

function infoController(threeDimView_, $scope) 
如果我将其与
$scope
一起传递给控制器,我会得到一个错误:

Error: Unknown provider: threeDimView_Provider <- threeDimView_

错误:未知提供程序:threeDimView\u提供程序您可以尝试将其配置为服务,如下所示:

var app = angular.module("yourapp",[]);
app.service("threeDimView",threeDimView);
无论何时要在控制器中使用它,只需将其声明为参数:

function infoController(threeDimView, $scope) 

将对象注入控制器而不是访问全局变量或在函数中创建对象的想法是允许单元测试。

我喜欢@khanh的答案,但我可能建议使用角度工厂,而不是服务。下面是一个例子:

没有全球范围:

app.factory('threeDimView', function(){
    return new threeDimView();
});
var _threeDimView_ = new threeDimView();
app.factory('threeDimView', function(){
    return _threeDimView_;
});
全球范围:

app.factory('threeDimView', function(){
    return new threeDimView();
});
var _threeDimView_ = new threeDimView();
app.factory('threeDimView', function(){
    return _threeDimView_;
});
然后您可以在控制器中声明依赖项,如下所示:

function infoController($scope, threeDimView){
    // use the threeDimView object (its already instantiated)
}

为什么不在您的控制器/范围中创建它?比如:
函数infoController($scope){$scope.threeDimView u=new threeDimView();}
如果对象是真正全局的,那么只需通过其名称就可以在控制器内访问它,而无需注入它。否则(或者如果您不想要全局状态),您可以在Angular服务中实例化对象,并将此服务注入任何其他需要它的组件。@Cherniv:这不好,因为它会妨碍单元测试。更好的方法是角度方式(将对象注入控制器)