2

can we add check undefined value in ng-init.? if there is value in scope then print it else print foobar. Currently, it should print foobar can we add a condition in ng-init ?

here is my code http://plnkr.co/edit/bFbAWXq6dKdkxWAxp7v8?p=preview

  <body ng-controller="MainCtrl" ng-init="test|| 'foobar'">
    <p>Hello {{test}}!</p>
  </body>
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
user944513
  • 12,247
  • 49
  • 168
  • 318
  • 1
    use basic JavaScript Syntax - http://stackoverflow.com/questions/3390396/how-to-check-for-undefined-in-javascript – cpoDesign Aug 08 '16 at 09:12

2 Answers2

1

It's that simple:

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

You can write almost everything as you write in a Javascript expression/line.

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>
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
0

Yes you can add conditions in ng-init

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

the value of test will be test itself if its defined, otherwise 'aasasas'

Syam Pillai
  • 4,967
  • 2
  • 26
  • 42