Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

angularjs - How to render only after a function has completed?

I had a list of objects defined in my controller, and was sorting it after vm.init() like this:

const myItems = [{},{},{}...{}]

vm.init().then(function() {
    $scope.ajaxLoading = true;    // Loader
    $scope.itemsToRender = [];
    // Pushing items from myItems in this list according to some conditions

    $scope.itemsToRender.sort(function(a, b) {
        return a.order - b.order;
    })
}).finally(function() {
    $scope.ajaxLoading = false;
});

This was working fine as expected,

but now I am getting myList from api response in vm.init(), and it does not sort the list when I come to this page. But if I reload the page, it sorts the list and renders perfectly.

I tried debugging and put console.log in the function, and the function was being called.

What am I doing wrong? Is the list rendering before sorting is complete? How do I fix this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

AngularJS needs to be aware of changes in order to digest and reflect those in the template. The sort() method you are using is Javascript, so despite applying it directly to the $scope.itemsToRender variable Angular is still not aware its content has changed, probably because it uses properties such as length for arrays, so if the length does not change it won't recognize those changes.

Anyway I'm pretty sure you can use the orderBy filter instead which will handle all this for you and it's the best practise for this case

<tr ng-repeat="item in itemsToRender | orderBy:'id'">

https://docs.angularjs.org/api/ng/filter/orderBy


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...