繁体   English   中英

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; 
}]);

UPDATE

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
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM