简体   繁体   中英

How do you use Angular JS to read multiple properties and values from a settings file?

I'm a bit new to Angular JS, and was hoping to figure out how to use an external settings file in conjunction with my app. Currently, I have my code running in a way that allows me to import my settings.js file.

var settings = {

    options : {
        foo : "video",
        bar : .8
    }

    colors : {
        top : "#FF0000",
        bottom : "FF00FF"
    }
}

My issue, is that my settings file will have a lot of different properties and values. As is, my code has me write out line by line the settings that I'd like to use. In the example, this will be foo and bar . How can I go about avoiding this?

Instead of having multiple lines of code, what logic could I use to simply allow me to read all the properties and values of my object?

You can see this in the example where I want to use settings.colors.accentColor and settings.colors.frameColor . My settings.js file might contain hundreds of different options, and I'll definitely have other categories of options (not just options and colors).

<div ng-app="settingsApp" ng-controller="settingsCtrl">
    <script src="Settings/settings.js"></script>

    <h1>Use video: {{ foo }}</h1>
    <h2>Colors</h2>
    <p>Background : {{ bar }}</p>
    <p>Accent : {{ settings.colors.accentColor }}</p>
    <p>Colors : {{ settings.colors.frameColor }}</p>
</div>
<script type="text/javascript" src="angular.min.js"></script>
<script>

  var app = angular.module('settingsApp', []);
    app.controller('settingsCtrl', function($scope, $http) {
      $scope.foo = settings.options.foo;
      $scope.bar = settings.colors.backgroundOverlay;
    });
</script>

Instead of doing it in that manner, try to load the file as json data directly. Here's is a good link where I learned how to use angularjs. Of course there are plenty other good ones too, but it's a matter of personal opinions and stuff. This guy also has tutorial video explaining each examples in the below link.

The example #20 is the one that may help you with your task

https://curran.github.io/screencasts/introToAngular/exampleViewer/#/

The answer was a lot more simple than I thought - thanks to help from a friend I figure out this solution.

<script>
    var app = angular.module('settingsApp', []);
        app.controller('settingsCtrl', function($scope, $http) {
            $scope.settings = settings;
        });
</script>

Simply put, I just attached the scope to the settings object I imported.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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