Issue with ng-show directive in AngularJS

Currently, I am developing a web app using AngularJS 1.6.6. In my template, I have implemented ng-show in order to recycle it:

<div >
    <br/>
    <div class="form">
        <form data-ng-submit="objectHandlerVM.functions.objectHandlerSwitcher()">
            <button data-ng-show="objectHandlerVM.functions.where('/editObject/'+objectHandlerVM.object.idn)">Edit</button>
            <button data-ng-show="objectHandlerVM.functions.where('/createObject')">Create</button>
            <button data-ng-show="objectHandlerVM.functions.where('/deleteObject/'+objectHandlerVM.object.idn)">Delete</button>
        </form>
    </div>
</div>

This setup is designed to display a different button based on the URL accessed. Below is the code snippet of the controller:

angular.module('objectApp')
.controller('objectHandlerCtrl', ['objectFactory','usersFactory','$routeParams','$location',
            function(objectFactory,usersFactory,$routeParams,$location){
    var objectHandlerViewModel = this;
    objectHandlerViewModel.object={};
    objectHandlerViewModel.functions = {
        where : function(route){
            return $location.path() == route;
        },
        readUserNameEmail : function() {
            usersFactory.getUser()
                .then(function(response){
                    objectHandlerViewModel.object.title= response.title;
                    objectHandlerViewModel.object.content= response.content;
                    console.log("Reading user with id: ",response.idn," Response: ", response);
                }, function(response){
                    console.log("Error reading user data");
                })
        },
        updateObject : function() {
            objectFactory.putObject(objectHandlerViewModel.object)
                .then(function(response){
                    console.log("Updating object with id:",objectHandlerViewModel.object.idn," Response:", response);
                }, function(response){
                    console.log("Error updating object");
                })
        },  
        createObject : function() {
            objectFactory.postObject(objectHandlerViewModel.object)
                .then(function(response){
                    console.log("Creating object. Response:", response);
                }, function(response){
                    console.log("Error creating the object");
                })
        },
        deleteObject : function(id) {
            objectFactory.deleteObject(id)
                .then(function(response){
                    console.log("Deleting object with id:",id," Response:", response);
                }, function(response){
                    console.log("Error deleting object");
                })
        },
        objectHandlerSwitcher : function(){
            if (objectHandlerViewModel.functions.where('/createObject')){
                console.log($location.path());
                objectHandlerViewModel.functions.createObject();
            }
            else if (objectHandlerViewModel.functions.where('/editObject/'+objectHandlerViewModel.object.idn)){
                console.log($location.path());
                objectHandlerViewModel.functions.updateObject();
            }
            else if (objectHandlerViewModel.functions.where('/deleteObject/'+objectHandlerViewModel.object.idn)){
                console.log($location.path());
                objectHandlerViewModel.functions.deleteObject(objectHandlerViewModel.object.idn);
            }
            else {
            console.log($location.path());
            }
            $location.path('/');
        }
    }
    console.log("Entering objectHandlerCtrl with $routeParams.ID=",$routeParams.ID);
    if ($routeParams.ID==undefined) objectHandlerViewModel.functions.readUserNameEmail();
    else objectHandlerViewModel.functions.readObject($routeParams.ID);
}]);

When trying to create an object and accessing the template, the URL should end with "createObject" for only one button to be displayed. The same rule applies to "editObject" and "deleteObject". However, all three buttons are being shown instead of just one.

I also attempted the following approach:

<button data-ng-show="objectHandlerVM.object.idn!=undefined">Edit</button>
<button data-ng-show="objectHandlerVM.object.idn==undefined">Create</button>

Even with this method, both buttons are still being displayed, causing further confusion...

Answer №1

ng-show functions with boolean values. If you need to verify the URL, you can create a function that checks the URL and returns true or false accordingly.

<button data-ng-show="verifyURL()">Edit</button>

Within the controller:

$scope.verifyURL = function(){
    //insert your logic here
    return true/false;
}

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

In the controller file, I plan to utilize a global variable for storing the user's session, ensuring it is securely saved for reference

In my web application about courses, I am faced with the challenge of saving a user's username throughout their session and then storing their progress in the database after completing a course. Instead of repeatedly asking the user to input their use ...

How can data be transferred from a parent to a child component in Angular?

I'm facing an issue trying to pass the selected value from a dropdownlist in a user interface. I have a parent component (app.component.html) and a child component (hello.component.html & hello.component.ts). My goal is to transfer the option val ...

How come ng-repeat isn't recognizing the function in the parent scope?

What is the reason for needing to use e in $parent.parentScopeFunc() rather than just e in parentScopeFunc() when {{ parentScopeValue }} works perfectly fine for showing parent scope members in a template? ...

Commitments when using a function as an argument

While I have a good understanding of how promises function, I often struggle when it comes to passing a function as a parameter: var promise = new Promise(function(resolve, reject) { // Perform asynchronous task ec2.describeInstances(function(err, ...

After converting from php/json, JavaScript produces a singular outcome

After running a PHP query and converting the result to JSON using json_encode, I noticed that when I try to print the results using echo, only one entry from the query is output in JSON format. My objective is to make this information usable in JavaScript ...

Positioning JQuery sliders

I've been working on a jQuery slider for my header, but I'm encountering an issue where the previous image drops down to the next container instead of staying in place and transitioning smoothly. It seems like there might be an error in my HTML/C ...

JavaScript code that triggers a page refresh when an input is added to a form without actually inputting

Upon delving into extensive research on this particular subject, I regrettably came up empty-handed. My sincere apologies if this question has been posed before. The task at hand involves creating a form that prompts users to input information about four ...

What is the most efficient way to save a document in mongoose based on a specific user's

Is there a way to ensure that when saving a template, it is associated with the user id? I have added a reference to the templateSchema for the User. User.model.js var UserSchema = new mongoose.Schema({ _id: { type: String, required: true, index: {uniq ...

How to retrieve the value of a selected radio button in an AngularJS radio button group that uses ng-repeat

In the following code snippet, I am trying to retrieve the value when any of the radio buttons is selected: <label ng-repeat="SurveyType in SurveyTypes"> <input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeN ...

How to toggle between arrays using ng-repeat

Currently, I am managing 3 arrays and wish to toggle between them using ng-repeat: $scope.fooDataObj = { array1:[{name:'john', id:'1'},{name:'jerry', id:'2'}], array2[{name:'bill', id:'1'},{name: ...

Switching Next.js JavaScript code to Typescript

I am currently in the process of transforming my existing JavaScript code to TypeScript for a web application that I'm developing using Next.Js Here is the converted code: 'use client' import React, { useState, ChangeEvent, FormEvent } fro ...

Generated a hierarchical JSON structure from a dynamically generated form

My client has a unique page builder that allows them to create web forms using a convenient drag and drop interface. Currently, the data is output in a JSON format like this: { "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

The transfer of character data from PHP to jQuery is not successful

Working with HTML files In this scenario, the values for the sub combobox are being retrieved through a PHP select query and these values are in character format. I have successfully tested passing integer values. <select name="sub" id="sub"> ...

The React Stripe API is functioning perfectly on local servers but encountering issues in the live environment

Just when I thought I was almost finished, reality hits me hard! My deadline is right around the corner! I finally got everything working on my local machine with a stripe payment form. However, when I pushed it live, I received an error message from my A ...

Data retrieval seems to be encountering issues in Firefox and IE9, whereas Chrome and Safari are functioning without any problems

I am using the following method function callCommentservice() { try { // Comment Service Url var getCommentServiceUrl = self.commentsServiceUrl + self.getRating + "tenantId=" + self.tenantId + "&ratedObjectTypeId=" + sel ...

[filepond] in order to enroll using the serverId value received from the server

Using 'filepond' within a Vue application is causing an issue. In the "process" function, the ID value obtained after transferring the file to the server (response.id) needs to be registered as 'serverId' of the file. Upon checking the ...

Localizing strings that are not saved in a database

Our web app will soon support multiple languages, a new feature we are excited to roll out! Currently, we utilize Handlebars for front-end templating and Node + Jade for back-end templating. As we prepare to implement language support, we're conside ...

After minifying the JS file, the $http service was not injected into the controller within a component

angular.module("datasView",[]) .component("datasView",{ templateUrl : 'dataview/datasview.template.html', controller : function control($http){ var self = this; $http.get('src/data/issues.json').then(function(res ...

Implementing stop loss with node-binance-api: A step-by-step guide

Currently utilizing node-binance-api for trading purposes. I have initiated an order by executing the following lines of code: let adjustLeverage = await binance.futuresLeverage(coin, 2); let res_2 = await binance.futuresMarketSell(coin, quantity); . Subs ...

Transform a flat 2D shape into a dynamic 3D projection using d3.js, then customize the height based on the specific value from ANG

Currently, I am utilizing d3.js version 6 to generate a 3D representation of the 2D chart shown below. Within this circle are numerous squares, each colored based on its assigned value. The intensity of the color increases with higher values. My goal is t ...