AngularJS: encountering an issue with undefined vm variable while implementing controllerAs syntax within a directive

I am having trouble accessing the vm.screensize property in the relevant controller. The error message states that vm is not defined. Below you can find the directive and controller code snippets.

    angular.module('app.ain.directives')
.directive('ainProjectWizardExplanations', function() {
    return {
        restrict: 'E',
        bindToController: true,
        scope : {
            sidenavHidden : '='
        },
        controller: 'ProjectWizardExplanationsController as vm',
        templateUrl: function() {
          console.log(vm.screensize, vm.animate);
            if(vm.screensize) {
                return 'app/ain/shared/directives/projectWizardExplanationsMobile.html';
            }else {
                return 'app/ain/shared/directives/projectWizardExplanations.html';
            }
        }
    };
});


    //controller
angular
        .module('app.ain.directives')
        .controller('ProjectWizardExplanationsController', ProjectWizardExplanationsController);

    function ProjectWizardExplanationsController($mdMedia,$scope,$rootScope, $timeout) {
                var vm = this;
                vm.animate = true;
                $scope.$watch(function() { return $mdMedia('sm'); }, function(small) {
                    vm.screensize = small;
                });
        }

Answer №1

Consider utilizing the "controllerAs" parameter while defining the directive.

.directive('customProjectExplanations', function() {
return {
    restrict: 'E',
    bindToController: true,
    scope : {
        sidepanelVisible : '='
    },
    controller: 'CustomExplanationsController',
    controllerAs: 'ctrl',
    templateUrl: function() {
      console.log(ctrl.windowSize, ctrl.animations);
        if(ctrl.windowSize) {
            return 'app/custom/shared/directives/projectExplanationsMobile.html';
        }else {
            return 'app/custom/shared/directives/projectExplanations.html';
        }
    }
};
});

Hoping this solution meets your requirements :)

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

Extract latitude and longitude data using Mapbox's autocomplete feature

Currently, I have integrated Mapbox with autocomplete in a Vue component: <template> <div> <div id='geocoder'></div> </div> </template> <script> import mapboxgl from 'mapbox-gl& ...

Designing functions with HTML

I have been working on creating a Coffeescript function that incorporates common HTML for an object that is frequently used on my page. To make the content dynamic, I am passing a variable to the function which will be replaced each time it is called. Unfo ...

Recognizing the click event on the checkbox within a <TableRow/> in ReactJS with MaterialUI

Using ReactJS and MaterialUI's component for tables, I have successfully created a table with two rows, each containing a checkbox. Now, the challenge is to create a method that can recognize when a checkbox is clicked and provide information about th ...

The continuous loop is triggered when attempting to pass array data from the API

Hello, I have been searching for a solution to my current issue without much success. The problem revolves around retrieving dates from Firebase and populating them into UI elements in my Vue app. My end goal is to align each date with the corresponding mo ...

Relaying event arguments from client-side JavaScript to server-side code-behind through ClientScript.GetPostBackEventReference

My goal is to initiate a postback using JavaScript and also pass event arguments. While I have managed to trigger the postback successfully, I am facing issues with passing event args. The function below is not functioning as expected. It seems to be enco ...

Why am I receiving the error message "Argument of type 'number' is not assignable to parameter of type 'never'?"

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { showSecret = false; logArr ...

Having trouble changing the chosen selection in the material UI dropdown menu

I've encountered an issue with my material ui code for a select dropdown. It seems that the selected option is not updating properly within the dropdown. <FormControl variant="outlined" className={classes.formControl}> <InputLabel ref={ ...

Do you know of a solution to fix the Stylelint error regarding semicolons when using CSS variables?

React.js Css in JS(Emotion) The components above are part of this setup. Here is the configuration for Stylelint: module.exports = { extends: [ "stylelint-config-standard", "./node_modules/prettier-stylelint/config.js", ], ...

Is the utilization of react-router for developing 'single-page applications' causing a depletion of server resources?

Hello, I am relatively new to the world of web development and would appreciate guidance on any misunderstandings I may have. Currently, I am immersing myself in learning the MERN stack. For my practice project, I am aiming to create a simple two-page webs ...

Angular component not transmitting any data through binding

I have a page with two components. Component A is named Dashboard, which displays a list of elements using ng-repeat. These elements, referred to as systems, are shown through Component B called SystemView. Each SystemView contains a list of log entries, a ...

How can I display table rows along with their child table rows in Angular?

Is there a way to display API data in a table using Angular? The table should have collapsible rows with nested child rows. This is the JSON file structure: { "collapse1": [ { "name": "Soil", "budget": 12345, "child": [ { ...

What language should be used for JSON data formats?

I am dealing with a JSON file named myjson.cfg that has the following structure: { "values": { "a": 1, "b": 2, "c": 3, "d": 4 }, "sales": [ { "a": 0, "b": 0, "c": 0, "d": 0, ...

A HTML input field that allows for multiple values to be populated by autofill functionality, similar to the features found

Can anyone assist me with creating a text box similar to the one in Facebook's new message feature? In that feature, we are able to add multiple people in the 'To' field, all of whom are suggested from our friend list. I would like to implem ...

Error: Attempting to access the 'url' property of an undefined variable, despite specifically checking for its undefined status

Within my React application, I am utilizing the following state: const [functions, setFunctions] = useState([{}]); I have created a test to check if a specific property is undefined: if (typeof functions[functionCount].url !== "undefined") { ...

What's the most efficient way to iterate through this Array and display its contents in HTML?

I'm struggling to sort a simple array and I think the issue might be related to the time format. I'm not sure how to reference it or how I can properly sort the time in this array format for future sorting. //function defined to input values ...

How can you run a function in JavaScript or TypeScript that is stored as a string?

Is there a way to call a function that is stored as a string? For example: var dynamicFun = `function Hello(person) { return 'Hello' + person; }` In this case, the dynamicFun variable can store any function definition dynamically, such as: var ...

How to use TypeScript to filter an array based on the values of another array

Suppose I have two arrays. The first one looks like this: names: [{ value: 'recordedData', desc: 'Data' } { value: 'recordedNumbers', desc: 'numbers' } { value: 'recordedNames', desc: 'name ...

Generating a new array and merging different sets of keys together

Is there a way to modify how items are added to a jQuery array? Here is the current code snippet in use: var sub_updated = []; $('.current-sub-items').each(function() { $(this).find('.prod-select').each(function() { if ($(th ...

Navigating through various Headers in ReactjsHandling different Headers in Reactjs

I am currently working on a project using Reactjs (Nextjs) and I need to have different headers for the home page compared to the rest of the pages. I have created a "Layout.js" file where I have placed the header and footer components, and then imported ...

Is it possible to exclude specific URLs from CSRF protection in sails.js?

I am currently integrating Stripe with my sails.js server and need to disable CSRF for specific URLs in order to utilize Stripe's webhooks effectively. Is there a way to exempt certain URLs from CSRF POST requirements within sails.js? I have searched ...