Is your ng-if not functioning properly with raw JavaScript?

I am attempting to verify the existence of a key within an object in an Angular $scope. Within my controller, I have defined this:

$scope.the_object = {'the_key': 123};

And in my template, I have included the following:

<span ng-if="'the_key' in the_object">
    the_key exists in the_object
</span>

However, upon inspection, I encountered the subsequent error in the console:

Error: [$parse:syntax] http://errors.angularjs.org/1.4.7/$parse/syntax?p0=in&p1=is%20an%20unexpected%20token&p2=11&p3='the_key'NaNn%20the_object&p4=in%20the_object
    at Error (native)
    at http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:6:416
    at Object.s.throwError (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:209:339)
    at Object.s.ast (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:202:118)
    at Object.sd.compile (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:211:203)
    at fc.parse (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:238:193)
    at b.$get (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:117:315)
    at n.a.$get.n.$watch (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:127:125)
    at a.link (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:254:214)
    at aa (http://52.29.xx.xx:5000/bower/angular/angular.min.js?version=1.4.7:73:90)

Can anyone advise on how to validate if the_key is present within the_object directly within the ng-if statement?

Answer №1

To check if the property you are looking for is within your object and not inherited, you can use the following code snippet.


<span ng-if="the_object.hasOwnProperty('the_key')">
    the_key exists in the_object
</span>

If the above condition does not apply and you are certain that you have not set the_key as undefined in your object, then you can utilize this code:


<span ng-if="the_object['the_key'] !== undefined">
    the_key exists in the_object
</span>

For further reference, please see this plunker

If all values in your object are ensured to be defined and not uninitialized, the second method mentioned above is more efficient than the first one. More information on this topic can be found at

Answer №2

To easily verify,

ng-if="obj.key !== undefined"

this code verifies if key exists within the obj. If it does, it will output true, and if not, it will output false. Existence here refers to not being undefined.

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

Discover the method for tracking idle time with jQuery and PHP

I have a script that utilizes PHP sessions through a custom class. One of the methods in this class calculates the remaining seconds before the session expires. Whenever the user refreshes the page or opens a new one, the idle time counter is reset using ...

Navigating AngularJS for User Authorization_REDIRECT

I've developed a login system using angularfire and firebase. Within this system, I have implemented a function that checks for the existence of authData when a user logs in or at other points in the application's flow. If authData is present, t ...

How using Bootstrap 4's 'data-toggle' attribute can impact the updating of AngularJS models

There has been talk about this issue in Bootstrap 3 with no official solution, but Bootstrap 4 doesn't seem to mention it. Take a look at the Plunker Demo showcasing the problem here The use of data-toggle on a radio input seems to cause the AJS mod ...

Tips for running multiple JavaScript functions in ASP.NET using Button's OnClientClick property

Is there a way to execute multiple JavaScript functions in ASP.NET to perform various tasks such as inserting a desired text in a TextBox, changing the TextBox background color and font color, and disabling or locking a Button for a specific duration? I ha ...

IE8 and IE9 encountering "Access is denied" error due to XML causing XDomainRequest (CORS) issue

Sorry if this seems repetitive, but I am unable to find a definitive answer to similar questions. Whenever I attempt to make a CORS request for XML, I consistently encounter an "Access is denied" JavaScript error in IE8. The code I am using is based on t ...

Search for text in multiple tables using jQuery and automatically trigger a button click event when the text is found

I am attempting to query certain tables and click a button within a cell of a specific table. Below is the code I am currently using: links[1].click(); iimPlayCode('WAIT SECONDS = 2') var compTabs = window.content.document.getElementById(' ...

Toggling markers according to form selections is not functioning

My goal is to dynamically show or hide markers on my Google Map that represent houses and condos, based on the features selected by the user from a select box with id #features. For example, if a user picks 'Swimming Pool' as a feature and click ...

What is the best way to send formatted date data to an API using react-datepicker?

I'm encountering an issue while attempting to send a date to my API using react-datepicker in conjunction with Formik to manage nested dates. Despite setting the dateFormat to yyyy/MM/dd, the value I receive is "2020-06-19T04:00:00.000Z". This value g ...

Error encountered: _moment2.default.date is not a recognized function within the React application

I keep encountering an issue when attempting to utilize a date from Moment.js in the constructor, componentWillMount, or componentDidMount. The error message I receive is: Uncaught TypeError: _moment2.default.date is not a function It's worth noting ...

Error encountered in Ionic Angular: Camera-Injection-Error provider is missing in Module.ts

Having some trouble while trying to develop an app with ionic-angular using the Ionic/ngx camera. I keep encountering this error even after adding the camera provider in the module.ts section. View the error here Below is my module.ts file content: impo ...

How can we pass a function to a child component in Vue 2.0?

I am facing a challenge with passing a function link to the child component in Vue. Although it is functioning correctly, the code appears in HTML format. How can I enhance this? In my Vue instance, I have: app = new Vue({ ... some code data: { ...

Updating state of an array nested inside an object using React and ES6

I'm fairly new to Javascript and I feel like my lack of fundamental knowledge might be hindering me from solving this issue. Despite trying different approaches and reading tutorials, I can't seem to get it right. My goal is to manipulate the st ...

Repeated data submissions occur when using a modal form

I have a dataTable List with buttons attached to each row as shown below: https://i.sstatic.net/9vujB.png When a button is clicked, a Modal form is displayed. The modal is uniquely generated for each row in the table and has a different ID. https://i.ss ...

How to fetch a single document from a nested array using Mongoose

Currently, I am working on a MongoDB database using Mongoose in Node.js. The collection structure resembles the following: { cinema: 'xxx', account: 'yyy', media: { data: [{ id: 1, name: 'zzz& ...

"Two columns of identical width, each occupying 50% of the screen height

I am currently working on a design featuring two columns, each set to occupy 50% of the width. I am facing a challenge with ensuring that the height of these columns stretches to the full height of the screen, even when they are empty, so I can showcase th ...

New issue with installing npm cra

Recently updated to npm version 6.14.4 and encountered an issue while trying to create a new app with cra-template. How can I resolve this problem? npx create-react-app sphinx.ui.react Error Log 50 timing stage:runTopLevelLifecycles Completed in 5234ms ...

error encountered in NestJS: unable to modify headers once they have been sent

request /login/login.html redirect /login I made a change to the redirect within the interceptor export class UricheckInterceptor implements NestInterceptor { constructor(private uri: string[]) {} intercept(context: ExecutionContext, next: CallHa ...

Styling a JSON message using AngularJS

I need help formatting the JSON message to match the required style. The desired format of the JSON message is as follows: [ { “question”: “Write down Nhat’s email”, “answer”: “<a href="/cdn-cgi/l/email-protection" class="__cf ...

Is there a way in PHP to establish a database connection only once and reuse it multiple times via Ajax calls in JavaScript?

My current setup involves using Ajax to request a remote PHP file for accessing the database. However, every time I make a request, the connection is re-created. Is there a way for me to create the connection just once and reuse it multiple times? The PHP ...

Automatically submit form in Javascript upon detecting a specific string in textarea

Just getting started with JS and I have a question that's been bugging me. I have a simple form set up like this: <form method="POST" action="foo.php"> <textarea name="inputBox123"></textarea> <input type="submit" value="Go" name ...