简体   繁体   English

如何处理AngularJS中的错误

[英]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. 我刚开始学习angular.js,我想显示Controller中定义的数组,但是当我尝试显示其显示空白页面时。 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. 我知道是否可以将post1中的ng-repeat = post更改为posts中的ng-repeat = post”,它可以正常工作。但是我想在控制台或浏览器中显示错误。请有人可以帮助我。

 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. 使用ng-if指令检查“ post1”是否未定义并显示错误消息。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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