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>
1

2 Answers 2

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="[email protected]" 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>

Sign up to request clarification or add additional context in comments.

Comments

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.