2016-01-19 54 views
3

我想將一個字符串綁定到作用域var,該作用域將通過用戶輸入在視圖內的輸入字段中獲取其值。 因此,連接到作用域var值的字符串應顯示在視圖中的另一個div中。如何在視圖內將字符串綁定到作用域var?

它應該是這樣的:

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

但這裏的問題是,單詞「Hello」已經顯示用戶輸入之前作出。我想在用戶輸入時將它與範圍var的值一起顯示。

回答

2

可以使用大量不同的方法... ng-if或使用三元表達式是其中兩個

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

或者

<div>{{userInput ? "Hello" + userInput :''}}</div> 
0

添加您自己filterifEmpty如下:

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

     return "Hello "+input; 
    } 
}); 

,然後用它作爲

<div>{{ userInput | ifEmpty:''}}</div> 
1

試試這個

Name: <input ng-model="userInput" placeholder="Enter your input..."/><br> 
<div ng-show="!!userInput">{{ "Hello" + userInput}}</div> 
0

你可以在用戶輸入使用ng-if

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