3

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}
]
2
  • 2
    Remove $scope.loadContent(); from your controller and add it as ng-init="loadContent" in your view. Commented Oct 21, 2016 at 8:04
  • Its very strange, could you can put your json, and this json is well loaded? Commented Oct 21, 2016 at 8:04

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome. Also consider adding ng-cloak to your body to stop the browser displaying uncompiled angular code whilst the JSON is being loaded. docs.angularjs.org/api/ng/directive/ngCloak. Obviously, if your JSON is local, this is never really an issue...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.