如何检查AngularJS中的undefined?

时间:2016-08-08 09:07:33

标签: angularjs angularjs-directive angularjs-scope

我们可以在undefined中添加检查ng-init值吗?如果范围内有值,则打印它,否则打​​印foobar。目前,它应该打印foobar 我们可以在ng-init中添加条件吗?

这是我的代码 http://plnkr.co/edit/bFbAWXq6dKdkxWAxp7v8?p=preview

  <body ng-controller="MainCtrl" ng-init="test|| 'foobar'">
    <p>Hello {{test}}!</p>
  </body>

2 个答案:

答案 0 :(得分:1)

就这么简单:

<body ng-controller="MainCtrl" ng-init="test = test|| 'aasasas'">
    <p>Hello {{test}}!</p>
</body>

您可以在Javascript表达式/行中编写几乎所有内容。

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

});
<script data-require="angular.js@1.0.x" src="http://code.angularjs.org/1.2.0rc1/angular.js" data-semver="1.0.7"></script>
<div ng-app="plunker" ng-controller="MainCtrl" ng-init="test = test|| 'aasasas'">
  <p>Hello {{test}}!</p>
</div>

答案 1 :(得分:0)

是的,您可以在ng-init

中添加条件
<body ng-controller="MainCtrl" ng-init="test = test ? test: 'aasasas'">
 <p>Hello {{test}}!</p>
</body>

test的价值如果已定义,则test本身为private const double R_MAJOR = 6378137.0; private const double R_MINOR = 6356752.3142; public MapPoint PointToWGS84(double x, double y) { double originShift = 2 * Math.PI * R_MAJOR / 2.0; double mx = (x / originShift) * 180.0; double my = (y / originShift) * 180.0; my = (180 / Math.PI) * (2 * Math.Atan(Math.Exp(my * Math.PI / 180.0)) - Math.PI / 2.0); return new MapPoint(mx, my, new SpatialReference(WGS84)); } ,否则为&#39; aasasas&#39;