Set Default Value to ng-bind in HTML
Asked Answered
D

3

18

I'd like to set a default value to scope, which is picked up by ng-bind. I am doing this like:

<button>Show <span data-ng-bind="data.text" data-ng-init="data.text = 'All';"></span> Names</button>

In this example, the span is set to innerHTML = 'All' when the page loads.

However, I was hoping there might be a way to do this without requiring the use of ng-init, maybe something like:

<button>Show <span data-ng-bind="data.text = 'All';"></span> Names</button>
Disgusting answered 11/9, 2014 at 14:42 Comment(1)
{{data.text || "All"}} (if you dont have an issue moving away from ng-bindRecha
P
18

In your controller:

$scope.data = {};
$scope.data.text = "All";

Your markup:

<button>Show <span data-ng-bind="data.text"></span> Names</button>

Or, if you want to skip the controller code (courtesy of Kohjah Breese' comment):

    <button>Show <span data-ng-bind="data.text || 'All'"></span> Names</button>

Presumably there will be some code elsewhere in your controller that will toggle this value, but for the purposes of initializing, that should do.

EDIT: Alternately, as tymeJV points out in the comments (ng-cloak added so {{}} syntax doesn't display to users):

<button>Show <span ng-cloak>{{data.text || "All"}}</span> Names</button>
Pithead answered 11/9, 2014 at 14:55 Comment(2)
This is also working, which the kind of thing I am looking for: <span data-ng-bind="data.text || 'All'"></span>Disgusting
For what it's worth, the codeschool.com beginning course (which is excellent, and I don't get paid to say that, etc.) uses this instead of $scope, but I'm guessing it's fairly standard practice to do so. Perhaps they use it in the next-level coursePithead
L
5

The || operator works also in ngBind like in pure JavaScript:

<span ng-bind="myVariable || 'My default value'"></span>

This outputs myVariable if the variable is filled, otherwise the alternative 'My default value' is used.

Libnah answered 19/6, 2015 at 11:31 Comment(0)
I
2

from angularjs doc :

The only appropriate use of ngInit is for aliasing special properties of ngRepeat [...] Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

So i guess initializing data.text in your controller is fine for angularjs

Insane answered 11/9, 2014 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.