avoiding the repetition of angularjs function

2019-09-09 07:30发布

I have the following function that parses a JSON file:

myApp.controller('myCtrl1', function($scope, $http, $compile, $interpolate, $templateCache) {
    $http.get('JSONFile1.json').success(function(data) {
        for (var i in data) {
            var interpolated = $interpolate($templateCache.get("Tpl1").trim())(data[i]);
            angular.element(document.querySelector("#loadTpl1")).append($compile(interpolated)($scope));
        }
    });
});

But I have several JSON files that I need to parse separately. If I want to parse this file, I have for each file write a similar function again, like:

myApp.controller('myCtrl2', function($scope, $http, $compile, $interpolate, $templateCache) {
        $http.get('JSONFile2.json').success(function(data) {
            for (var i in data) {
                var interpolated = $interpolate($templateCache.get("Tpl2").trim())(data[i]);
                angular.element(document.querySelector("#loadTpl2")).append($compile(interpolated)($scope));
            }
        });
    });

so the functions are further multiplied. All the functions are the same but have different IDs.

How can I put all these same looking functions in a function so that I could parse every JSON file in a function and write less code?

Edited:

the content of the json File (example):

[
  {
    "_comment": "Launch Camera Button",
    "type": "button",
    "id": "cameraBt",
    "icon": "ion-android-camera",
    "name": "Launch Cam",
    "toPage": "",
    "color": "white",
    "function": "takePicture()",
    "controller": "CameraCtrl",
    "backgroundcolor": "#0066FF",
    "font-size": "20px"
  }
]

the call of the function from html:

<div ng-controller="myCtrl1" id="loadTpl1">
                <script type="text/ng-template" id="Tpl1">
                    <a style="color:{{color}}; background-color:{{backgroundcolor}};" id="{{id}}" class="{{type}}" href="{{toPage}}" ng-controller="{{controller}}" ng-click="{{function}}">
                        <i id="{{iconid}}" class="{{icon}}">{{texticon}}{{linebreak}}</i>
                        <br>{{name}}
                    </a>
                </script>
            </div>

As can be seen, I can add HTML components in the page or delete them from the JSON file. This is everything what the function above makes.

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-09 07:50

it would be best to create a directive, which calls your custom JSON service like this:

myApp.factory('jsonGetter',['http', function( $http ) {

    return function( $id ) {

        return $http.get('JSONFile' + $id + '.json');

    }

}]);

myApp.directive('jsonData',['$scope', '$compile', '$interpolate', '$templateCache','jsonGetter', function() {
    return {
        scope: {
            id: '='
        },
        tempalteUrl:'jsonTemplate.html',
        link: function( scope, $elm ) {

            jsonGetter( scope.id ).then(function( data ) {

                // I assume that data is an array where 
                // there is an object you specified in your answer
                angular.extend( scope, data[0] );

            });

        }
    };
}]);

In jsonTemplate.html:

<a ng-style="{ 'color' : color,'background-color': backgroundcolor }"  id="{{id}}" class="{{type}}" href="{{toPage}}" ng-controller="{{controller}}" ng-click="{{function}}">
<i id="{{iconid}}" class="{{icon}}">{{texticon}}{{linebreak}}</i>
<br>{{name}}
</a>

When we call the directive as below, it uses the service to get the data based on the id, then extend the scope of the template with the server data:

<json-data id="1"></json-data>
查看更多
登录 后发表回答