AngularJS如何包含来自其他文件的数组

AngularJS how to include array from other file?

本文关键字:文件 数组 其他 何包含 AngularJS      更新时间:2023-09-26

我在控制器中定义了一些相当大的二进制(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
});