Search code examples
javascriptarraysangularjsangularjs-ng-include

AngularJS how to include array from other file?


I have some rather large binary (200kb) arrays defined inside a controller. Now I want to put these large arrays in seperate files, and somehow include them or get hold of them in my controller.

Is there an elegant way of doing this? Could I maybe put the arrays in different services, and then get the arrays from the services?


Solution

  • Just to elaborate on @hansmaad's answer and provide a demo

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

    Updated JSFiddle