使用 AngularJS 进行条件绑定,如果属性不为空,则连接并绑定值 [英] Conditional binding with AngularJS, concatenate and bind value if property is not empty

查看:23
本文介绍了使用 AngularJS 进行条件绑定,如果属性不为空,则连接并绑定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 的新手,如果值 !== 为空,我正在尝试将字符串绑定到模型.这适用于一个输入,但我想将多个文本输入组合成一个字符串.

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>

推荐答案

现场演示(点击).

如果您想隐藏整个元素,您可以简单地将 ng-showng-hide 指令添加到 h3 本身.

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 : ''}}

说明:

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>

根据您的评论,您可能还希望返回一个带有函数的绑定:Live演示(点击).

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:

JavaScript:

$scope.foo = '';
$scope.bar = function() {
  return 'added value '+$scope.foo;
};

这篇关于使用 AngularJS 进行条件绑定,如果属性不为空,则连接并绑定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆