3

I want to bind a string to a scope var which will get its value by user input in an input field inside a view. So that the string concatenated to the scope var value should display in another div in the view.

It should be something like that:

<body ng-controller="MainCtrl">
Name: <input ng-model="userInput" placeholder="Enter your input..."/><br>
<div>{{ "Hello" + userInput}}</div>

But the problem here is that the word "Hello" displays already before the user input is made. I want to display it together with the value of the scope var when the user input it.

user2985035
  • 569
  • 3
  • 8
  • 18

4 Answers4

2

Can use numerous different approaches ... ng-if or use a ternary in expression are two of them

<div ng-if="userInput">{{ "Hello" + userInput}}</div>

Or

<div>{{userInput ?  "Hello" + userInput :''}}</div>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

Try this

Name: <input ng-model="userInput" placeholder="Enter your input..."/><br>
<div ng-show="!!userInput">{{ "Hello" + userInput}}</div>
jkris
  • 5,851
  • 1
  • 22
  • 30
0

Add your own filter say ifEmpty as in below:

angular.module('app').filter('ifEmpty', function() {
    return function(input, defaultValue) {
        if (angular.isUndefined(input) || input === null || input === '') {
            return defaultValue;
        }

        return "Hello "+input;
    }
});

and then use it as

<div>{{ userInput | ifEmpty:''}}</div>
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
0

You could use an ng-if on the user input.

<p ng-if="userInput">Hello {{userInput}}</p>
denixtry
  • 2,928
  • 1
  • 21
  • 19