Exploring the World of Angular Directives

I've been attempting to achieve something that should be straightforward in theory. Despite my efforts to find a solution through Google, I have yet to come across anything that has successfully worked for me. My current setup involves Angular JS version 1.4.9. Here's what I aim to accomplish:

<site-menu>
   <site-menu-item title="Search" href="#/search"/>
   <site-menu-item title="Reports" href="#/reports"/>
   <site-menu-item title="About" href="#/about"/>
</site-menu>

The desired outcome is as follows:

<ul>
   <li><a href="#/search">Search</a></li>
   <li><a href="#/reports">Reports</a></li>
   <li><a href="#/about">About</a></li>
</ul>

My intention is to implement this functionality as a directive so that when a user clicks on one of the links, an "active" CSS class can be applied to the LI element. Unfortunately, despite my best efforts, I've struggled to make it work. Personally, transclusion and compiling (if these are indeed required) have always been areas where I've faced challenges with Angular 1.x.

If anyone has any insights or suggestions, I would greatly appreciate it!

Thank you in advance!

Answer №1

I have created a simple directive to handle this functionality without the need for transclusion or compiling. It would be helpful in the future if you provide more specific details or code snippets.

Here is an example of how you can use this directive:

(function(angular) {
  'use strict';

  angular.module('app', [])
    .directive('siteMenu', [function () {
      return {
        restrict: 'AE',
        scope: {
          menus: '='
        },
        controller: SiteMenuController,
        controllerAs: 'vm',
        bindToController: true,
        templateUrl: 'site-menu-template.html'
      };

      function SiteMenuController() {
        var vm = this;

        vm.selected = 0;

        vm.onClick= function(index) {
          vm.selected = index; 
        };
      }
  }])

  .run(['$templateCache', function($templateCache) {
    $templateCache.put('site-menu-template.html',
      '<ul>' +
        '<li ng-repeat="menu in vm.menus" ng-click="onClick($index)" ng-class="{active: $index == vm.selected}">' +
          '<a ng-href="#/{{ menu }}">{{ menu }}</a>' +
        '</li>' +
      '</ul>'
    );
  }]);
})(window.angular);

To use the directive, include the following code in your HTML:

<site-menu menus="['search', 'reports', 'about']"></site-menu>

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

Tips for organizing a collection of items similar to an array

I am facing a challenge with sorting a list of JSON objects based on a unix timestamp field within each object. To tackle this issue, I created a sorting function function sortUnixTimestamp(a, b){ var a = parseInt(a.timestamp); var b = parseInt(b.time ...

Tips for contacting the giveaway host after the giveaway has finished

I am currently utilizing the Discord Giveaways module. I am interested in learning how to send a direct message to the host of the giveaway once it has ended. I haven't quite figured out how to do that yet. Here is what I have gathered so far: manag ...

Issue encountered while validating a dropdown selection within a form using JavaScript

I have a form that includes multiple options for users to choose from. My goal is to prevent users from selecting the same option more than once. I've written some JavaScript code for this purpose, but I'm encountering an issue with the alert mes ...

How to use AngularJS $http to make an external image request

I created a Plunker to showcase my attempt at retrieving an external image through an $http call. My goal is to return the URL upon successful retrieval with a status 200, and display a placeholder 'Image not available' if a 404 error occurs. Cl ...

The style of MUI Cards is not displaying properly

I've imported the Card component from MUI, but it seems to lack any styling. import * as React from "react"; import Box from "@mui/material/Box"; import Card from "@mui/material/Card"; import CardActions from "@mui/m ...

Error encountered with MobileFirst version 8 and Angular JS v1.5.3 integration using Bootstrap

I am encountering an issue with my Cordova application that integrates with MobileFirst Platform version 8, Ionic version 1.3.1, and AngularJS version 1.5.3. Upon bootstrapping AngularJS to connect the app to MobileFirst Platform, I encounter the following ...

Validation of Date in Angular 5 (with specified minimum and maximum dates)

Struggling to find a simple solution for this issue, I have a date input like the following: <input [(ngModel)]="toolDate" type="text" class="tool_input tool_input__date"> To control the input and restrict it to only accept dates, I am using . In m ...

What is the best method for looping through a JSON object string?

Here is the JsonResult I received: [{"name":"Group 1"},{"name":"Group 2"},{"name":"Group 3"}] I'm a little confused about how to iterate over this data or retrieve the values of the name inside the buildSelect function within the editoptions in jqGr ...

Fastify endpoint failing to respond to designated URL

Within my code, there is a router setup: fastify.get('/:link', (req, reply) => { req.params.url = req.host+req.url; reply.view("template.ejs",req.params); }); I am trying to capture URLs and process them in the template. All URLs are ...

Do we still need to configure XSRF-TOKEN on the server even when using HttpClientXsrfModule?

Would implementing the code below in app.module be sufficient to protect against XSRF/CSRF on the client side? HttpClientXsrfModule.withOptions({ cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN' }) Alternatively, is additional ...

The most effective method for verifying a user's login status using node.js and express and updating the client-side HTML

For my web application, I am using node.js and express along with sessions in mongoDB to handle server side code like this: exports.home = function(req, res){ if(req.session.userEnabled){ console.log("logged"); res.render('home', { title ...

Passing a string to a function in AngularJS through ng-click

How can I pass a string to a function using ng click? Here's an example: HTML <a class="btn"> ng-click="test(STRING_TO_PASS)"</a> Controller $scope.test = function(stringOne, stringTwo){ valueOne = test(STRING_TO_PASS); } Edit - ...

Creating a multi-tiered cascading menu in a web form: Harnessing the power of

In my form, there is a field called 'Protein Change' that includes a multi-level dropdown. Currently, when a user selects an option from the dropdown (for example, CNV->Deletion), the selection should be shown in the field. However, this funct ...

Storing information in local storage as JSON using AngularJS

I am working on a form with the following fields: <form ng-submit="addState()"> <input ng-model="text1" type="text"> <input ng-model="text2" type="text"> <input ng-model="text3" type="text"> ...

Trigger function when the element is generated

Is there a way to execute a function only once while still having it run each time a new element is created using v-for? <div v-for"value in values"> <div @ function(value, domElement) if value.bool===true @> </div> ...

Exploring Vue.js: Enhancing Button Functionality with Select Range

I have a question regarding button selection in a v-for loop. I need to allow users to select options from A to C, as shown in the graphic. Additionally, users should be able to press another button like D. <menu-item v-for="(item, index) in me ...

What are the limitations of sorting by price?

One issue I am facing is that the sorting functionality in the sortProductsByPrice (sortOrder) method doesn't work properly when products are deleted or added. Currently, sorting only applies to products that are already present in the this.products a ...

Unable to get Mongoose's Required field to work in conjunction with Enum validation

Encountering issues with Mongoose Required true and Enum validation when using updateone await MonthlyTarget.updateOne({website: req.body.website, year: req.body.year, month: req.body.month}, req.body, {upsert: true}); Model 'use strict'; import ...

Utilizing Node.js and Express alongside EJS, iterating through objects and displaying them in a table

Today I embarked on my journey to learn Node.js and I am currently attempting to iterate through an object and display it in a table format. Within my router file: var obj = JSON.parse(`[{ "Name": "ArrowTower", "Class" ...

activating the button once all fields have been completed

Currently, I am utilizing knockout.js for data binding. There is a form with fields for name, number, email, etc. If any of these fields are left blank and the save button is clicked, the button becomes disabled as expected. However, if I later fill in th ...