Trouble arises with the extent of a unique directive's scope

Greetings! I currently have a custom directive that looks like this:

mainApp.directive('myMenu',function(){
        return {
            restrict : 'E',
            scope :{menuItems : "=menuItems"},
            compile: function(element, attributes) {
                var linkFunction = function($scope, element, attributes){
                    for (i = 0;i<$scope.menuItems.length;i++){
                         element.append('<li><a href="#home">'+$scope.menuItems[i].name+'</a></li>');
                    }
                }
                return linkFunction;
            }

        }
    });   

I am implementing it in my HTML page as shown below:

<my-menu menuItems="menuItems"></my-menu>

However, when I check the console, I encounter an error message stating TypeError: Cannot read property 'length' of undefined

Answer №1

One issue that may arise is during the linking phase where the menu items might not have been loaded yet, resulting in $scope.menuItems being undefined.

An alternative approach would be:

var mainApp = angular.module('my-app', [], function() {})

mainApp.controller('AppController', function($scope) {
  $scope.menuItems = [{
    name: 'one'
  }, {
    name: 'two'
  }, {
    name: 'three'
  }, {
    name: 'four'
  }];
})

mainApp.directive('myMenu', function() {
  return {
    restrict: 'E',
    scope: {
      menuItems: "="
    },
    template: '<ul><li ng-repeat="item in menuItems">{{item.name}}<a href="#home"></a></li></ul>'
  }
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js"></script>

<div ng-app="my-app" ng-controller="AppController">
  <my-menu menu-items="menuItems"></my-menu>
</div>


If using a template is not feasible, then consider this alternative:

var mainApp = angular.module('my-app', [], function() {})

mainApp.controller('AppController', function($scope) {
  $scope.menuItems = [{
    name: 'one'
  }, {
    name: 'two'
  }, {
    name: 'three'
  }, {
    name: 'four'
  }];
})

mainApp.directive('myMenu', function() {
  return {
    restrict: 'E',
    scope: {
      menuItems: "=menuItems"
    },
    link: function($scope, element, attributes) {
      $scope.$watch('menuItems', function(value) {
        element.empty();
        angular.forEach(value, function(item) {
          element.append('<li><a href="#home">' + item.name + '</a></li>');
        });
      });
    }

  }
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js"></script>

<div ng-app="my-app" ng-controller="AppController">
  <my-menu menu-items="menuItems"></my-menu>
</div>

Answer №2

The problem arose from the naming convention I utilized - for example, in a directive, 'menu-items' should be used instead of 'menuItems'. The issue was resolved by changing 'menuItems' to 'menu'.

Answer №3

Call

$scope.$eval(attributes.menuItems)
within the compile function to retrieve the menu items

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 does Python interpret arrays from JavaScript?

As part of my API setup, I am sending parameters to a python script. One of these parameters happens to be a JavaScript array. Interestingly, when I check the array in Python, it only shows the first index. Here is the snippet of my Angular JS get request ...

The delete function in aspx.cs never seems to be triggered from the .aspx file

I am encountering an issue with deleting items from a list, as my delete function in the .aspx.cs file is not being called. Below is my JavaScript code: function doTheDelete(doIDeleteExpenses) { if (selectedExpensesList.length > 0) { ...

Prevent selection of weekend dates in Angular Bootstrap datepicker with a personalized directive

I have integrated the Angular Bootstrap datepicker plugin into my Angular application. To customize the date pickers in my app, I created a custom directive. In certain places, I need to disable weekends in the date picker. I have added the functions to d ...

ng-class not functioning properly when invoked

In my controller, I have the following function: $scope.menus = {}; $http.get('web/core/components/home/nav.json').success(function (data) { $scope.menus = data; $scope.validaMenu(); }).error(function () { console.log('ERRO') }); ...

Form submission not being recognized by Ajax's .done() function

I'm trying to include a form from another file using ajax. It's a simple form that is activated by an onclick event defined as follows: <a href="javascript:void(0);" class="remitir" title="Reemitir Solicitud" data-id="'.$value['idso ...

Preventing FlatList from scrolling when re-sizing

Resizable from the re-resizable package is causing my Flatlist not to scroll properly. Despite having enough elements to trigger scrolling, it fails to do so when the resizable element is present. This issue does not occur when the resizable element is rem ...

When Infinite Scroll is integrated into another file with HTML tags stacked on top, it will not load additional posts when scrolling down

I have implemented an Infinite Scroll feature that dynamically loads more data from a database as users scroll to the bottom of the page. However, I encountered an issue when trying to include this functionality in another .PHP file. If I insert any HTML ...

Tips for obtaining the combined outcome of multiple arrays (3 to 5 arrays) in JavaScript

How can we transform an array of objects with nested arrays into a new array of objects with mixed values? Consider the following input: var all = [ { name: "size", value: [20, 10, 5], }, { name: "color", value: [ ...

When implementing fancybox within bxslider, numerous thumbnails are shown simultaneously

My issue arises when using fancybox within bxslider. Once I open an image, multiple thumbnails start repeating themselves endlessly. This problem only started occurring after adding bxslider. Any thoughts on why this might be happening? ...

Res.end isn't halting the script's execution process

I'm currently facing an issue while building an API around a third-party API in my Express route. The problem is that the script keeps executing even after encountering a 406 error. Below is the snippet of my code: app.get('/submit/:imei', a ...

Retrieve the callback arguments using sinon.spy within a JavaScript promise

During my test with mocha and sinon, I encountered an issue where I couldn't retrieve a callback value from inside a promise scope of an HTTP-request due to the asynchronous nature of promises. It seems that by the time sinon.spy checks on the callbac ...

Change URL link after login user with javascript

Is there a way to generate a URL link based on the user's name (gmail)? For example: The code below is somewhat suitable for my needs. However, I am trying to figure out how to automatically retrieve the username and populate it in the input field. ...

I am experiencing issues with the POST method in my RESTAPI in node.js and it is not functioning

I recently started learning Node.js and Express.js with the goal of creating a basic API to retrieve data from a JSON file using the GET method, and to add a new user using the POST method. The GET method is functioning correctly, but I have encountered a ...

What is the best way to have my transparent navigation bar float on top of my background in a parallax-scrolling website?

Currently, I am working on creating a website with a navigation bar that has no background and floats on top of a background image. However, I am facing an issue with my parallax-scrolling website. Whenever the page is scrolled to the second section, the n ...

What is the best way to establish anchors for *ngFor elements in Angular 2 and beyond?

I have a component that displays items using *ngFor. My goal is to scroll down to the element with anchor #3. Here's the code snippet: @Component({ selector: 'my-app', template: ` <button (click)="scroll(3)">scroll 2</butt ...

Is there a method in JavaScript to access the object to which a function was originally bound?

I have a curiosity about making the code below function properly, capturing the logging as instructed in the comments. function somePeculiar(func) { var funcThis = undefined; // Instead of undefined, how can we access // ...

When delving into an object to filter it in Angular 11, results may vary as sometimes it functions correctly while other times

Currently, I am working on implementing a friend logic within my codebase. For instance, two users should be able to become friends with each other. User 1 sends a friend request to User 2 and once accepted, User 2 is notified that someone has added them a ...

Including code that is tailored specifically for the Internet Explorer browser on Windows Phone devices

While testing the Google Maps API on different browsers and devices, I encountered issues with Windows Phone. It turns out that Google Maps is not supported on Windows Phones, resulting in errors. How can I set it up so that instead of displaying the map ...

Adding to an existing array in MongoJS

I have been attempting to append data to an existing array in my mongoDB. The code snippet below is what I currently have, but unfortunately, it does not work as expected since all the existing data gets wiped out when I try to add new data: db.ca ...

Is there a way to avoid waiting for both observables to arrive and utilize the data from just one observable within the switchmap function?

The code snippet provided below aims to immediately render the student list without waiting for the second observable. However, once the second observable is received, it should verify that the student is not enrolled in all courses before enabling the but ...