Using conditional binding with AngularJS, the value will only be concatenated and bound if the property is not empty

As a beginner with Angular, I am attempting to link a string to a model as long as the value is not empty. This is successful for a single input, but I now want to merge multiple text inputs into a single 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></span>

Answer №1

Check out the live demo here (click).

If you want to hide the entire element, you can simply include the ng-show or ng-hide directive within the h3 tag.

Another option is to use ternary in the binding to decide what should be bound:

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

Here's an explanation:

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

In your code, it would look like this:

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

Based on your feedback, you might also want to return a binding with a function: View the live demo with function (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;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Difficulty with Bootstrap 4 mobile navbar dropdown feature

<div class="baslik baslik1 baslik2 "> <nav class="navbar bg-light navbar-light navbar-expand-sm sticky-top "> <a href="./index.html" class="navbar-brand"><img src="img/512x512logo.png" ...

Accessing a JavaScript variable in another <script> section

I'm facing a challenge where I need to access a JavaScript variable that is declared in one block of an HTML page from another block on the same page. This is crucial for me to be able to halt an AJAX call that is currently ongoing. However, I'm ...

Conditionally Add Columns to jQuery Datatables

I am working with a jQuery datatable to showcase data retrieved through an AJAX request. However, I am interested in adding a third column to the table specifically for administrators, allowing them to delete entries. Can someone guide me on how to incorpo ...

What is the process for attaching an analytics tag to data messages using the Firebase Admin SDK with Javascript or TypeScript?

Adding a label to my message is something I'm trying to do. I checked out the official guidelines here and found a similar question answered on Stack Overflow here. I've been attempting to implement this in JavaScript, but I'm stuck. Here& ...

Is it possible to relocate a function that relies on the success callback of Ajax outside of the callback?

According to JSHint.com: Avoid placing function declarations inside blocks. Opt for a function expression or move the statement to the outer function's top. JSHint advises against keeping this function within the success callback. function matchC ...

Quicker Solution to Iteration in Google Apps Script with JavaScript

I've set up a for loop to extract sales data from an array (salesLog) and transfer it to a designated sheet (targetSheet) in columns. The sales data is spread across multiple columns in the array. The loop adds up the columns between columnStart and c ...

What is the best way to modify the state of a particular element in an array when using useState in React?

In my Next.js application, I am using a useState hook to manage state. Here is how my initial state looks like: const [sampleData, setSampleData] = useState({ value1: '', value2: '', value3: [] }); To update the state ...

Exploring the features of Three.js: materials and shadows

I cannot figure out why the mesh material I chose is causing issues. As you can see in the image: https://i.sstatic.net/4nijf.png The black objects look fine, with smooth and correct shadows. However, the white objects appear strange and the shadows, in m ...

Clicking the button will cause the React component to close itself automatically

Is there a way to make a React component self-close when a button within the component is clicked? Take a look at this code snippet: import React from 'react'; import PropTypes from 'prop-types'; const MyReactComponent = (props) => ...

Navigating with Next.js Router: Dynamic URLs and the power of the back button

Utilizing the Router from the package next/router allows for a dynamic URL and loading of different content on the page: Router.push('/contract', `/contract/${id}`); An issue arises where the back button does not function as expected after runni ...

What are the similarities between using the map function in AngularJS and the $map function in jQuery?

I am currently in the process of migrating jQuery code to AngularJS. I have encountered some instances where the map function is used in jQuery, and I need to replicate the same functionality in AngularJS. Below is the code snippet that demonstrates this. ...

Oops! Property 'month' cannot be set on undefined value due to a TypeError

Despite not receiving any errors from Visual Studio Code, I’m encountering an error in Chrome's console. Below is the code snippet from my interfaces.ts file: export interface Data1{ month: string; employeeName: string; date: string; employmentSta ...

What are some methods for singling out a specific table row?

When working on my app, I faced the task of importing a JSON file and displaying its contents in a table with 3 columns. However, there are two main issues that arose: Utilizing array index for the row key is not recommended due to the table also having ...

Creating a stylish Go URL bar using HTML and CSS

Looking for some guidance in JavaScript as I am new to it. I want to create a go bar similar to the ones found at the top of browsers using HTML and JS. When the button is clicked, it should navigate to the URL entered in the box. Here's an example of ...

Is there a method to track the number of active onSnapshot listeners from Firestore in my application?

In my app, I am implementing a feature that dynamically removes query onSnapshot listeners and replaces them with new ones. To ensure that resources are properly freed up, I need to test the effectiveness of the unsubscribe function. Unfortunately, I do n ...

Encountering an issue with the autocomplete feature in the jQuery library where it is stating "this.source is not a function."

Here's the code snippet I'm working with: $.ajax({ type: "GET", url: "https://url.com", dataType: "json", success: function (data) { $("#search").autocomplete({ source: data, select: function (even ...

Angular confirmation, confirmation after tweaking

Currently, I am using angular along with angular-confirm. I have created an interface containing a list of buttons. To view the interface, you can visit this link: Each button in the list has a confirmation prompt attached to it like so: <button ng- ...

No response text returned from the local Ajax request

Currently, I am facing a challenge while attempting to send an ajax call from the client to my server containing data related to an input parameter. The issue is that although I can view the data in my server's console, it does not display in the brow ...

What could be the reason behind the unexpected behavior of my Bootstrap 3 carousel?

I'm attempting to replicate this visual effect in my own carousel, featuring semi-transparent images on the left and right sides. However, I'm encountering a negative result with my project when transitioning between slides at : here. This is th ...

Awesome method of redirecting outdated URLs to the most recent established URL

My website heavily relies on JavaScript and communicates with a .NET C# RPC service. We encountered an issue where clients' browsers cached the JavaScript, so we decided to add a version number to the URL in order to force them to use the latest JavaS ...