Dealing with AngularJS variables that are undefined when attempting to refresh the view from the controller

I am currently learning AngularJS and attempting to transform my webpage using the "angular way" instead of relying on jQuery. However, I am facing some challenges in understanding how to achieve this.

This is how my HTML looks:

<body style="padding-top: 0px;" data-spy="scroll" ng-app="SummerMill">
    <section id="intro" class="main style1 dark">

        <!-- Header -->            
        <header ng-controller="MainController" id="header">

            <!-- Logo -->
            <h1 id="logo">Summer Mill</h1>

            <a ng-mouseover="locations()"
                style="color:black;text-decoration:initial;"
                id="logoii"
                href="http://localhost/locations">Locations</a>

            <!-- Nav -->
            <nav id="nav">
                <ul class="nav navbar-nav">
                    <li ng-repeat="headerLink in headerLinks"><a ng-init="content=headerLink.text" href="#{{content}}">{{content}}</a></li>
                </ul>
            </nav>
        </header>

Below is my controller script:

app.controller('MainController', ['$scope', function($scope) {
    $scope.headerLinks = [ 
        { 
            text: 'Intro', 
            alternativeText: 'Arlington'
        },
        { 
            text: 'Wholesale', 
            alternativeText: 'New York'
        }
    ];

    $scope.locations = function() {
        content = headerLinks.alternativeText;
    }
}]);

Essentially, I want the content inside the <li> element to change when hovered over. While the hover event is triggered correctly, I receive an error stating ReferenceError: headerLinks is not defined. This seems strange as it is declared in the controller itself. I attempted to resolve this by changing

content = $scope.headerLinks.alternativeText;
, which removed the error but it appears that the content variable in the controller is different from the content variable used in ng-init.

Could you guide me on the correct approach to accomplish this task? It's possible that I may be approaching this problem the wrong way.

Answer №1

To improve your code, consider simplifying it by using ng-if and a flag called isOver.

angular.module('app',[])
       .controller('MainController',function($scope){
  
   $scope.headerLinks = [ 
        { 
            text: 'Intro', 
            alternativeText: 'Arlington'
        },
        { 
            text: 'Wholesale', 
            alternativeText: 'New York'
        }
    ];
$scope.locations = function() {
    content = headerLinks.alternativeText;
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!-- Header -->            
<header ng-app="app" ng-controller="MainController" id="header">

        <!-- Logo -->
  
        <h1 id="logo">Summer Mill</h1>
        <a ng-mouseover="isOver=true" ng-mouseout="isOver=false"
                style="color:black;text-decoration:initial;"
                id="logoii"
                href="http://localhost/locations">Locations</a>

        <!-- Nav -->
                <nav id="nav">
                    <ul class="nav navbar-nav">
                        <li ng-repeat="headerLink in headerLinks">
                          <a ng-if="!isOver" href="#{{headerLink.text}}">{{headerLink.text}}</a>
                          <a ng-if="isOver" href="#{{headerLink.alternativeText}}">{{headerLink.alternativeText}}</a>
                      </li>
                    </ul>
                </nav>

</header>

You can also use a ternary operator instead of ng-if like this:

angular.module('app',[])
       .controller('MainController',function($scope){
  
   $scope.headerLinks = [ 
        { 
            text: 'Intro', 
            alternativeText: 'Arlington'
        },
        { 
            text: 'Wholesale', 
            alternativeText: 'New York'
        }
    ];
$scope.locations = function() {
    content = headerLinks.alternativeText;
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!-- Header -->            
<header ng-app="app" ng-controller="MainController" id="header">

        <!-- Logo -->
  
        <h1 id="logo">Summer Mill</h1>
        <a ng-mouseover="isOver=true" ng-mouseout="isOver=false"
                style="color:black;text-decoration:initial;"
                id="logoii"
                href="http://localhost/locations">Locations</a>

        <!-- Nav -->
                <nav id="nav">
                    <ul class="nav navbar-nav">
                        <li ng-repeat="headerLink in headerLinks">
                          <a href="#{{!isOver ? headerLink.text : headerLink.alternativeText}}">{{!isOver ? headerLink.text : headerLink.alternativeText}}</a>
                      </li>
                    </ul>
                </nav>

</header>

Alternatively, you can simplify the code even further:

angular.module('app', [])
  .controller('MainController', function($scope) {

    $scope.currentText = 'text';
    $scope.headerLinks = [{
      text: 'Intro',
      alternativeText: 'Arlington'
    }, {
      text: 'Wholesale',
      alternativeText: 'New York'
    }];
    $scope.locations = function() {
      content = headerLinks.alternativeText;
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!-- Header -->
<header ng-app="app" ng-controller="MainController" id="header">

  <!-- Logo -->

  <h1 id="logo">Summer Mill</h1>
  <a ng-mouseover="currentText='alternativeText'" ng-mouseout="currentText='text'" style="color:black;text-decoration:initial;" id="logoii" href="http://localhost/locations">Locations</a>

  <!-- Nav -->
  <nav id="nav">
    <ul class="nav navbar-nav">
      <li ng-repeat="headerLink in headerLinks">
        <a href="#{{headerLink[currentText]}}">{{headerLink[currentText]}}</a>
      </li>
    </ul>
  </nav>

</header>

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

How to insert a JSON object into a nested array using JavaScript

I am currently facing an issue with adding a JSON object based on specific conditions to an array, which is then used to create a WINJSList. The problem arises when I try to access the elements of the list or array after using the array.push method. My goa ...

Implementing non-blocking asynchronous object return in a node.js function

Struggling with a function that accesses data from a JSON file and queries it for a specific key. Unfortunately, the return function seems to be executing before the query can find the key. Even after querying and attempting to return the variable queryre ...

Decreasing the height of a div that wraps a slider

Currently, I am using a slider and would like to showcase its functionality. Here is the demo link: I have tried wrapping this slider in a div element, but it unexpectedly decreases the height to 125px from the original 100%. Here is the original code: ...

Apply a different class to a group of elements when hovering over them, excluding the element being hovered on

I need to blur multiple elements on my website when I hover over them, leaving only the hovered element in focus. Is there a more efficient way to achieve this? Currently, I have the following code: $(function() { $('#a').hover(function() { ...

The pdf generation feature of pdf-creator-node in Linux seems to be malfunctioning

An error occurred with code EPIPE at afterWriteDispatched (internal/stream_base_commons.js:154:25) at writeGeneric (internal/stream_base_commons.js:145:3) at Socket._writeGeneric (net.js:784:11) at Socket._write (net.js:796:8) ...

emulate clicking on a child component element within the parent component's test file

In my testing scenario, I encountered a challenge in simulating the click event of an element that exists in a child component from the parent test file. let card; const displayCardSection = (cardName) => { card = cardName; }; describe('Parent ...

Is there a way to upload a file using express/multer without triggering a redirect?

Note: Despite coming across this post, I couldn't find it helpful. Other related posts were focused on angular/react, which are not relevant to my current project. I have implemented a file upload feature that should provide a response indicating whe ...

Sending a function return to a React component

What I want to achieve is sending the response from an API call to a React Component and using it to generate a List. My confusion lies in how to pass the value from a function to the component. Do I require state for this process? searchMealsHandler(even ...

Optimize your React application by eliminating debug code before deploying it to production

Currently, I am developing a React App within an npm environment. Throughout my JavaScript code, I have the following snippet in multiple JS files: ... let url = loc.protocol + "//" + loc.hostname + (loc.port ? ":" + loc.port : "") + "/" + baseUrl; if (D ...

Transforming intricate JSON data into a structured table format

I'm struggling to transform the nested JSON data into an HTML table, but I keep encountering an error. I'm uncertain about where I may have made a mistake. Could it be related to how I am trying to access the array within the object? Here' ...

The login controller fails to retrieve any values upon submission

My current controller setup looks like this: var myApp = angular.module('myApp', ['ui.router']); myApp.controller('loginController',['$http', function($http) { this.loginForm = function(){ console.log(th ...

Guide on accessing the text content within a div element in HTML by triggering a button click

To extract specific text from multiple div tags, I need to trigger an event when clicking a button. <div class="col-lg-3 col-md-6 mb-4"> <div class="pricing-table pricing-secondary"> <div class="price-hea ...

What is the best way to duplicate a text using a button in ReactJS?

Hey there, I'm working with an array and trying to figure out how to copy the text in a p element ({item.adress} => this is part of an array item) when a button is clicked. Could you lend me a hand? import classes from './CryptoBox.module.css& ...

The router.push function does not properly redirect to the specified path; instead, it just reloads the current page

I am a newcomer to NextJS and facing a challenge where I need to transfer data from the current page to another page. However, instead of loading the defined path in router.push as pathname: "/booking/checkout/", it loads the current page. I wan ...

Unable to retrieve scope data in controller function

Having trouble accessing the scope attribute fullName from the controller method login. What could be causing this issue? App.controller('LoginController', ['$scope', 'LoginService', '$location', function(scope, Log ...

The CSS property overflow:hidden or overflow:scroll is not functioning as expected when applied to a

On my practice website, I have set up a demonstration for showcasing text data. The issue arises when the user inserts an excessive amount of characters in the text box. To address this, I would like the text to be scrollable so that all content can be d ...

Guide to saving output to a file using node.js and express

I have developed an application using node.js and express.js on top of elasticsearch. The application is quite simple, featuring a search box that returns results in JSON format when querying for a specific keyword. For example, searching for the word "whi ...

Determine whether the elements in the master array match the elements in the child array

Checking for data presence in arrays: [ { "productDisplay": "ZXP 105", "productNumber": "WZDR 112" }, { "productDisplay": "ZXP 106", "productNumber": "WZDR 113" } ] ChildArray [{productDisplay:"ZXP 105", ...

Is there a way to programmatically select an HTML tab or filter in puppeteer?

I am currently developing a web scraping application for a website that utilizes tab headers to filter the contents of a table. In order to extract the data from the table, I need to first select a specific filter by clicking on a tab item. However, I&apos ...

Creating an AJAX URL in an external JavaScript file within a Django project

How can I verify if a student user's email exists in the database using keyup event in a registration form, and prevent form submission if the email is already registered? Below are the relevant files for achieving this: urls.py urlpatterns = [ ...