Conditional binding with AngularJS, concatenate and bind value if property is not empty

后端 未结 1 819
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-17 10:45

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 stri

相关标签:
1条回答
  • 2021-01-17 11:26

    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;
    };
    
    0 讨论(0)
提交回复
热议问题