Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Default Value to ng-bind in HTML

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>
like image 462
Kohjah Breese Avatar asked Sep 11 '14 14:09

Kohjah Breese


People also ask

How do I set default value in Ng?

Use ng-init to set default value for ng-options . Save this answer.

What is Ng-bind in HTML?

The ng-bind-html directive is a secure way of binding content to an HTML element. When you are letting AngularJS write HTML in your application, you should check the HTML for dangerous code. By including the "angular-sanitize.

What is difference between ng model and Ng-bind?

ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable. Save this answer.

What is data Ng-bind?

The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable, or expression, changes, the content of the specified HTML element will be changed as well.


1 Answers

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>
like image 118
MrBoJangles Avatar answered Oct 14 '22 06:10

MrBoJangles