Is it possible to incorporate variables when utilizing NG-CLASS for an active link in Angular?

I am trying to create a navigation using a loop in my code. However, I keep encountering an error which says that it won't evaluate as a string. The idea is to loop through the $scope.navigation and use it to generate the navigation dynamically instead of manually writing out each list and anchor tag.

  <!DOCTYPE html>
  <html ng-app="Sample">
    <head>
       <title>Sample Angular App</title>
       <script src="Scripts/basket.js"></script>
       <link rel="stylesheet" href="css/global.css"/>
       <script src="Scripts/angular.min.js"></script>
       <script src="controllers/main.js"></script>
       <script src="routes/route.js"></script>
  </head>
   <body>
     <div class="navigation" ng-controller="AppCtrl">
         <ul class="cf" >
            <li class="link {{link.name}}" ng-class="{{link.name + 'Active'}}" ng-repeat="link in navigation">
              <a href="{{link.route}}" ng-click="setActive($index)">{{link.name |      uppercase}}</a> 
            </li>
        </ul>
     </div>
     <div class="wrapper">
       <div ng-view>

       </div>
     </div>
   </body>
  </html>

This is how my main js script file is structured:

          function AppCtrl($scope) {

            $scope.navigation = [

                { name:"main", route:"#/"},
                { name:"edit", route:"#/edit" },
                { name: "save", route: "#/save" },
                { name: "settings", route: "#/settings" }

            ];

            $scope.currentPage = null;

            $scope.setCurrentPage = function (index) {

                $scope.currentPage = $scope.navigation[index];

            }

            $scope.setActive = function (index) {

                angular.forEach($scope.navigation, function (value, key) {

                   $scope[value.name + 'Active'] = "";

                });

             var active = $scope.navigation[index].name;

                $scope[active + 'Active'] = "active";


            }

        }

I'm facing an issue where the {{link.name}} is not being evaluated as a string even though it is one. Is there a way to resolve this problem and successfully loop through $scope.navigation to output the navigation dynamically while also incorporating the setActive function? As a beginner with angularjs, I am unsure if this approach is allowed or if there are constraints that need to be addressed.

Answer №1

If you want to set an active CSS class in a more efficient and easier way, consider saving a single value in your scope that represents the active state. This can be achieved by creating a function like this:

$scope.setActive = function (index) {    
  $scope.activeIndex = index;
};

Then, using ng-class, you can provide a map where "the names of the properties whose values are truthy will be added as CSS classes to the element" (Source: http://docs.angularjs.org/api/ng.directive:ngClass).

With this approach, you can easily apply the CSS class based on whether the current $index matches the activeIndex:

ng-class="{active: $index == activeIndex}"

Answer №2

After testing the dnc253's suggested solution, it appears to no longer be effective.

To address this issue, I created a new method:

$scope.isActive = function(index){
    return $scope.activeIndex === index;
};

Within the HTML code:

ng-class="{active: isActive($index)}" 

This modification seems to resolve the problem.

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

Access the node within a template's conditional statement

For my website built with polymer, I have created a custom element where data is loaded via ajax. To display the correct content based on the current state of loading, I use <template if="{{}}"> elements like this: <polymer-element name="modules- ...

Creating a JavaScript Redirect Modal in Laravel

When a user likes a story on the card, they can save it by clicking the "save" button. I handle this action by calling the savePost function in my .js file. However, if the user is not logged in, I redirect them to the login page using "location.replace( ...

The value of 'id' is consistently unspecified when using Leap Motion

I am new to programming with Leap motion and I have a specific question about my code: Leap.loop(function(obj) { var hands = obj.hands.map(function(d) { return { id: d.id, length: d.length, palmPositionX: d ...

Activate flashlight on web application using JavaScript and HTML through phone's browser

I need help figuring out how to activate a phone's flashlight within a web app using JavaScript and HTML. I successfully developed a web app that scans QR codes using the phone's camera. While I managed to activate the camera, I encountered chall ...

What steps should I take to generate a stylized date input in javascript?

Looking to dynamically create a date string in JavaScript with the following format: dd-MMM-yyyy Need the dd part to change between 1 and 29 each time I generate the variable within a loop Month (MMM) should be set as Jan ...

Utilize Node.js Socket.IO to trigger CodeIgniter controller function calls

As a beginner with Node.js and socket programming, I am looking to utilize a php function within my nodejs socket program. I am unsure if this is achievable, so any assistance or guidance on how to do so would be greatly appreciated. Thank you in advance ...

What could be causing the console to display undefined?

Can anyone help me with an issue I'm having while making an AJAX call using fetch and promises? I have successfully displayed the temperatures, but for some reason, the location is showing up as undefined. Here is the code snippet: function getWeat ...

Using JavaScript, you can filter an array of objects based on a specific search input

I am in the process of implementing a filtering feature for a list using React, but surprisingly, I haven't been able to find any useful resources online to guide me through this common task. Currently, I have an array of users that I need to filter ...

The jQuery selector is unable to locate the IMG element using its unique ID

I'm experiencing an issue with a webpage that includes the following code snippet: <img class="img-qrcode" id="img_123.000.00.01" src="http://localhost:7777/data/code_img\123.000.00.01.png" alt="./data/code_img\123.000.00.01. ...

req.body returns as an empty object

I'm currently utilizing body-parser, but it seems to be malfunctioning without any clear indication of what the issue might be. app.js var createError = require('http-errors'); var express = require('express'); var path = require ...

Error message stating: "Unable to read property 'then' as it is undefined within Angular nested promises."

I'm having trouble passing data back from a service to a controller in my AngularJS application. The service I am calling inside a factory makes an HTTP request for JSON data and then needs to modify it before returning it to the controller. However, ...

Evaluate my API Manager

Hello, I am currently diving into the world of JavaScript backend development. My latest project involves building a RESTful API using node.js, express.js, sequelize.js with MySQL as my database. To test my skills, I have successfully created a basic Tasks ...

Employing both Angular 1 and Angular 2 in conjunction

As a newcomer to angular, this is my first experience. My ultimate goal is to incorporate the following component into Angular 2: While I have some knowledge of JavaScript, I am attempting to integrate an Angular 1 library into an Angular 2 project. Aft ...

Logging entire line syntax along with string output for debugging purposes

In my Vue.js application, there is a method that I have implemented. It goes like this: methods: { searchFunction(helper) { //helper.addFacetRefinement('deal', 'deal').search(); helper.addFacetRefinement('pri ...

Quicker method for displaying an element in an array than utilizing a for loop

Having an array as shown below: var arra= new String [50,50]; // New entries are added to the array and for each row added, count is increased by 1. The columns go up till incount which is always less than 50. for(i=0;i<=count;i++) { for(j=0;j<in ...

The hover effect and image opacity adjustment seem to be malfunctioning in my HTML/CSS code

Currently, I am in the midst of a web project and my goal is to implement a hover effect on the first card containing an image. The desired outcome is for the card to move upwards upon hovering, allowing the image to become fully visible with an opacity se ...

Injecting a service into another service

Having trouble injecting one service into another one, although each works fine when tested separately. The project structure is as follows: app.html includes app.js, service1.js, service2.js, and they are positioned in a specific order. Here is the code ...

A guide on exposing TypeScript classes globally through a WebPack bundle in JavaScript

Currently delving into TypeScript, my aim is to gradually replace JS with TS. However, due to having numerous JS files, my strategy involves creating new classes in TS and incorporating them into my existing JS files for the time being. Eventually, I plan ...

How can a JS script determine the shape of a quadrilateral based on its properties?

Hi there! I'm new to coding and could use some guidance. I've been given a task to create a script that takes input for the length of each side and the angles of each corner in order to determine whether the shape is a square, rectangle, rhombus ...

Exploring the wonders of JQuery's $.each() method in combination with

My code seems to be facing an issue with the last part, where I have an array containing some data. var dArray = { 'var1': $("#var1").val(), 'var2': $("#var2").val(), 'var3': $("#var3").val(), 'var4' ...