简体   繁体   中英

How to handle errors in AngularJS

I am new to angular.js just started learning, i want to Display the array defined in the Controller, But When I am trying to Display Its Showing empty page. I know if i change the ng-repeat=post in post1 to ng-repeat=post in posts" it ll work. But i want show the Error either in the Console or in the Browser. Please Can anybody help me.

 var mainapp = angular.module('mainApp', []); mainapp.controller('control', function ($scope) { $scope.posts = [ {title: 'post 1', upvotes: 5}, {title: 'post 2', upvotes: 2}, {title: 'post 3', upvotes: 15}, {title: 'post 4', upvotes: 9}, {title: 'post 5', upvotes: 4} ]; }); 
 <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script> </head> <body ng-app="mainApp" ng-controller="control"> <div ng-repeat="post in post1 | orderBy:'upvotes'"> <p>{{post.title}}-upvotes {{post.upvotes}}</p> </div> </body> </html> 

This is not an error at all from angular point of vew. In fact it is quite usual to use variables in template which are undefined for now, but will get some value later.

Ie imagine that you have in controller:

$timeout(function() {
    $scope.post1 = [{title : 'test'}];
}, 100)

Use ng-if directive to check "post1" is undefined and display error message.

<div ng-repeat="post in post1 | orderBy:'upvotes'">
    <p>{{post.title}}-upvotes {{post.upvotes}}</p>
</div>

<div ng-if="post1==undefined">
     Error Message
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM