Thursday 15 May 2014

angularjs - Controller with ngResource method called indefinitely -


I decided to start learning AngularJS by making a simple app.

The server-side application is created with ExpressJs, but the resources used below ( / movie /: id ) have not yet been implemented, so the URL Pointing to an 404 (not found) error so only '/' works.

I wanted to see how a resource was treated, so I did this simple test:

  var app = angular.module ("app", ["ngresource "]); App.factory ("Movie", function ($ resource) {return $ resource ("/ movie /: id");}) app.controller ("MovieCtrl", function ($ radius, movie) {$ scope.test = Function () {movie.quiry (); return 42;}});   

and my template file:

  & lt; Div ng-app = "app" & gt; & Lt; Div ng-controller = "MovieCtrl" & gt; {{Test ()}} & lt; / Div & gt; & Lt; / Div & gt; As expected, the template has been provided and '42' has been displayed properly, but if I look at the console in the Chrome Developer Tools, I see the following error (also expected):  <   GET http: // localhost / movie 404 (not found)   

But this message is printed indefinitely and never stops , As if my movie tries to reach / movie , even if After a hundred efforts also fails.

Thanks in advance.

This is because movie.query () call $ Scope After $ $ () it receives a response from the server.

Every time the value of $. $ Applied () is called , angular examines dirty (which again calls test ) and hence call Movie.query () then From) to know that anything has changed. This causes an infinite loop.

Run movie.quiry () to test () , and it should work.

Let me clear myself - look at this pseudo code:

  var watches = ['$ scope.test ()']; Var previous = {}; Var values ​​= {}; $ Rootscope. $ Apply = function () {prefix = value; Value = {}; Var filthy = wrong; For (var i = 0; i & lt; watches; lb; i ++) {var expression = clocks [i]; Value [expression] = value = eval (expression); If (value = last!) Dirty = true} if (dirty) $ rootsecope $ Apply (); } Movie.query = function () {setTimeout (function () {$ rootScope. $ Apply ();}, 300); } $ Scope.test = function () {Movie.query (); Return 42; }   

The flow is the following:

  1. $ scope.apply ();
  2. $ scope.test ();
  3. Movie.query (); - & gt; setTimeout ($ scope.apply, 100) (back from the beginning);

    and so on ..

No comments:

Post a Comment