17

I am new to Angular and am trying to bind a string to a model if the value !== empty. This work for one input, but I would like to combine multiple text inputs into one string.

<input type="text" ng-model="data.source">
<input type="text" ng-model="data.medium">     

<span ng-show="data.source"><h3>{{'additionToSource' + data.source}}</h3></span>
<span ng-show="data.medium"><h3>{{'additionToMedium' + data.medium}}</h3>
1
  • Using ng-show and ng-hide are probably what you want in this case. Commented Feb 3, 2014 at 22:05

1 Answer 1

33

Live demo here (click).

You could simply add the ng-show or ng-hide directive to the h3 itself if you are wanting to hide the whole element.

Alternatively, you could use ternary in the binding to determine what is bound:

{{foo ? 'some string '+foo : ''}}

Explanation:

foo //if $scope.foo is truthy (not empty)
? 'some string '+foo //bind a string with $scope.foo concatenated to the end
: '' //otherwise, bind in an empty string

For your code, it would be:

<h3>{{data.source ? 'additionToString' + data.source : ''}}</h3>

Based on your comments, you may also be looking to return a binding with a function: Live demo (click).

<input ng-model="foo">

<h3 ng-show="foo">{{bar()}}</h3>
<h3>{{foo ? bar() : ''}}</h3>

JavaScript:

$scope.foo = '';
$scope.bar = function() {
  return 'added value '+$scope.foo;
};
Sign up to request clarification or add additional context in comments.

2 Comments

How could I bind that <h3> to an additional <h3>. Would I create another model inside the <h3>?
@CoreyRab you should update your question to be more clear...I'm not sure what you mean. Do you mean something like this? jsbin.com/AYOrofo/5/edit I just use a function to return the formatted string.

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.