Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Load Json Error

I'm an Angular beginner. I want to load a json on load, this works well but if I make a change to an input field, I get an error message.

Error: $rootScope:infdig Infinite $digest Loop

Thanks

My HTML

<body ng-app="myApp" ng-controller="mainCtrl">
<div id="wrapper">
    <header style="height:50px;"> </header>
    <div class="container">
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
        <script src="js/controller.js"></script>
        <section>
            <div class="col-md-4">
                <label for="words">Wörter</label>
                <input ng-model="words" id="words" type="number" name="words" placeholder="Wörter" min="10" max="10000" value="{{words}}" step="10"> 
            </div>
            <p>{{words}}</p>
            <div id="view" class="col-md-6">

                <ul ng-controller="loadContent">
                    <li ng-repeat="content in contents | orderBy:random">{{content.text}}</li>

                </ul>
            </div>

        </section>
    </div>
</div>

My javascript

var app = angular.module('myApp', []);
app.controller('mainCtrl', function ($scope, $http) {
    $scope.words = 40;
    $scope.letterLimit = 400;
});
app.controller('loadContent', function ($scope, $http) {
 $scope.random = function () {
        return 0.5 - Math.random();
    }
 $scope.loadContent = function() {
     var def = $http.get('data.json').success(function(data) {
         $scope.contents = data;
     });
 }
 $scope.loadContent();
});

My json

[
{"text": "Lorem ipsum1", "date" : true},
{"text": "Lorem ipsum2", "data" : true},
{"text": "Lorem ipsum3", "data" : true}
]
like image 425
captain_keller Avatar asked Dec 06 '25 16:12

captain_keller


1 Answers

I think that angular is continuously disgesting your controller as soon as you interact with the view, and is therefore executing $scope.loadContent(); at the bottom of your controller repeatedly.

I assume you only wish for this to fire once? If so, remove the function call from your controller and modify your view as below.

<body ng-app="myApp" ng-controller="mainCtrl" ng-init="loadContent">

With this, $scope.loadContent is only called once. if you wish to call it another way, or multiple times, please specify in your question.

like image 175
IronAces Avatar answered Dec 08 '25 05:12

IronAces



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!