AngularJS - bind / view function that returns a promise

I posted the problem in the gythub AngularJS, but it doesn't seem to get much attention, and I was not able to fix it myself, as this is a pretty low problem, so I think it's time to look for a workaround.

Angular allows you to put a promise (or anything with a .then(...) function) in your scope, and once it is resolved, all $ watch and everything associated with that promise will use the resolved value. The problem arises when you use a function to return a promise, because the same does not apply - it is treated as a simple object.

For instance:

 var helloDef = $.Deferred(); $scope.hello = helloDef.promise(); $scope.getHello = function() { return $scope.hello; }; $timeout(function() { helloDef.resolve('Hello!'); }, 1000); 

Fiddle

Here, using ng-bind="hello" works fine and outputs Hello !, but ng-bind="getHello()" outputs [object Object], since the internal $ watch returns the promise object. Works similarly with $ q instead of $ .Deferred.

In my actual code, I create a promise the first time the function is called, so I can’t just keep the promise and refer to it in scope.

I also need this more than just ng-bind, so making my own binding directive that handles this case correctly is not viable.

Does anyone have any ideas? I am currently returning a promise if the data was not resolved and the actual result, if any, but this is a pain to work with. Everything related to data briefly causes strange side effects when loading data, such as ngRepeat, using a promise object instead of an allowed value to create elements.

Thanks.

UPDATE: Request for choice: https://github.com/angular/angular.js/pull/3605

UPDATE 2: For future reference, automatic clearance of promises was deprecated in section 1.2.

+4
source share
2 answers

The query request , it should be fixed in 1.2.0, so I will mark this as an answer.

0
source

For some things, I use $ resource. If I need to wait for it, $ then works well:

 var r = $resource...get... var p = r.$then... 

Otherwise, I create my own resource-like object, which is not a promise, but has a promise that I can wait.

+1
source

Source: https://habr.com/ru/post/1496590/


All Articles