AngularJS如何包含来自其他文件的数组
AngularJS how to include array from other file?
我在控制器中定义了一些相当大的二进制(200kb)数组。现在,我想把这些大数组放在单独的文件中,并以某种方式将它们包含在我的控制器中。
有没有一种优雅的方法可以做到这一点?我可以把数组放在不同的服务中,然后从服务中获取数组吗?
您可以选择其中一个提供程序配方,将数组注入控制器、服务或指令。
https://docs.angularjs.org/guide/providers
恒定配方将是的良好开端
myApp.constant('bigArray', myArray);
只是为了详细说明@hansmaad的答案并提供一个演示
HTML
<div ng-app="myApp" ng-controller="myController">
<div ng-repeat="item in bigArray">
<h1>{{item.name}}</h1>
</div>
</div>
JavaScript
var app = angular.module("myApp", []);
//In another file
app.constant("BigArray", [
{
name: "Item 1"
},
{
name: "Item 2"
},
{
name: "Item 3"
}
]);
//In another file end
app.controller("myController", ["$scope", "BigArray", function($scope, BigArray){
$scope.bigArray = BigArray;
}]);
更新
HTML
<div ng-app="myApp" ng-controller="myController">
<div ng-repeat="item in bigArray">
<h1>{{item}}</h1>
</div>
</div>
JavaScript
var app = angular.module("myApp", []);
//In another file
app.constant("BigArray", new Uint8Array([0x10, 0x20, 0x30]));
//In another file end
app.controller("myController", ["$scope", "BigArray", function($scope, BigArray){
$scope.bigArray = BigArray;
}]);
更新的JSFiddle
您可以将数组分类在不同的服务文件中,并在控制器中注入这些服务以获得这些数组,然后可以在控制器文件中管理数据。您还可以将这些数组保存在简单的json文件中,并发出http-get请求以获得类似的数据
$http.get('/path to your file')
.success(function(data){
//logic
})
.error(function(data){
//capture error
});
相关文章:
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- 正在尝试将JSON文件放入JS数组
- React.js如何从js文件中获取数组
- 将大数组(字符串和类型数组的混合物)存储到blob或文件中/从blob或文件检索大数组的最佳方式
- JavaScript代码,用于在浏览器中显示字节数组中的PDF文件(非base64编码)
- 如何从txt文件中获取要在javascript数组中使用的对象
- 数组在手动写入时有效,但从文本文件加载时无效
- 在将csv文件中的数据分配给数组变量时增强了d3代码
- 将javascript数组写入文件
- 从不一致的文件路径数组中获取键的值
- 如何将json文件中的数据提取到对象数组中,并在两个控制器之间共享
- 读取外部local.txt文件以将数据加载到数组中
- 将文本文件读入数组
- Grunt 可以直接从文件对象/数组或 glob 中的“src”值通过 HTTP 加载远程文件
- 将 FormData 对象放入数组中以从不同的输入文件上载文件
- 如何使用 lodash 在 Json 文件的数组中仅获取具有特定 atribute 的对象
- 在外部.js文件中使用全局php数组
- 数组中每个文件的javascript长度
- 使用Javascript数组检测媒体文件并返回所有URL
- 从多个文件中推送文本的函数(使用html5文件读取器上传)返回数组