The issue with Angular directive controller not recognizing 'this' reference

I'm struggling with the code snippet below. The vm.name variable doesn't seem to be working as expected. Additionally, why is the this keyword inside the controller not being detected? I've defined a closed scope for the directive, so what could be causing this issue?

Can anyone spot what I am doing incorrectly here?

var mod = angular.module('myApp', []);

mod.directive('myObj', myObject);

function myObject(){
  return {
      restrict: 'E',
      templateUrl: 'my-obj.html',
      scope: {},
      controller: myController
  };

  function myController(){
    var vm = this;

    vm.name="vfdfbdn";
  }
}

Answer №1

If you want to access this in a controller within a directive, make sure to specify controllerAs: 'ctrl'. Then, in the template, you should prefix all names with {{ctrl.name}}, or alternatively utilize $scope like this:

function myController($scope) {
    $scope.name = "vfdfbdn";
}

Answer №2

function myComponent(){
  return {
      restrict: 'E',
      template: '<div>{{c.name}}</div>',
      scope: {},
      controller: myCtrl,
      controllerAs: 'c'
  };

  function myCtrl(){
    var vm = this;

    vm.name="vfdfbdn";
  }
};

To gain a deeper understanding on the topic, please refer to this related discussion.

Answer №3

In order to inform Angular about how you plan to reference the this from the controller in the view, you need to specify it.

function myObject(){
  return {
      restrict: 'E',
      templateUrl: 'my-obj.html',
      scope: {},
      controller: myController,
      controllerAs: 'ctrl'
  };
}

By setting up controllerAs as 'ctrl', you can access everything that was assigned to this and named as vm within your controller using ctrl.

The reason I chose to use ctrl is to illustrate that there doesn't have to be a direct connection between the name used to refer to it in the view (defined with controllerAs) and the name assigned to this inside the controller function. It's common practice to differentiate between controllers by utilizing unique controllerAs references so it's clear which controller they pertain to in the view.

Answer №4

Give this a shot:

const newObj = () => {
    return {
        restrict: 'E',
        templateUrl: 'my-obj.html',
        scope: {},
        bindToController: true,
        controller: objController
    };
}

objController.$inject = ['$scope'];

function objController($scope){
  var vm = this;
  vm.name="example";}

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 handling searches for strings and arrays of strings in JavaScript

_.get(params, "_q") can output either a string or an array of strings. In my current code, when I input "hello, there", it translates to an array of strings and results in an error saying h.get(...).trim is not a function. Please take a look at ...

What is the best way to transmit a 500x500 2D Integer Array using Websockets?

I'm encountering an issue where I believe it may be too time-consuming to JSON.stringify and send data to each individual user. For example, if 4 people connect at the same time, the server will become stalled during array parsing, resulting in signif ...

Tips for incorporating an outside model into vue.js with babylon js

Struggling with importing a gltf file into vue.js using babylon.js to create a 3D view on a webpage. The documentation online isn't very clear, and I've tried the following steps in my Hello.vue file: <div> <h1> Hello </h1> < ...

React: Render function did not return any content. This typically indicates that a return statement is missing

Can anyone help me troubleshoot this error? Error: CountryList(...): No render was found. This typically indicates a missing return statement. Alternatively, to display nothing, return null index.js import React from 'react'; import ReactDOM f ...

Adjusting the size of wrapper functions

One common issue I encounter is the need to wrap a function on an object for various reasons. Is there a sophisticated method to maintain the original function's length property on the wrapper function? For instance: var x = { a: function(arg1, ...

Setting the default value in a Reactive form on the fly: A step-by-step guide

When creating a table using looping, I need to set the default value of my Reactive Form to `Repeat` if the loop value matches a particular character, otherwise I want it to be empty. Here is my code: typescript rDefault:string = ""; create(){ ...

What is the reason `addEventListener` does not work with a class method?

Recently, I discovered that the listener passed to addEventListener can actually be an object with a handleEvent function instead of just a callback function (here). However, I encountered an issue when trying to use handleEvent as a class method: class F ...

Customizing the Accordion Header Icon in Bootstrap UI when Tab is Expanded

Is there a way to modify the accordion header icon when the tab is expanded? For the Accordion plunke URL click here: http://plnkr.co/edit/7HMhoHk9AWyBAHALgD0P?p=preview <accordion-group> <accordion-heading> I can have ma ...

JavaScript implementation of Twitter OAuth authentication

I searched far and wide for a strong example of a JQuery ajax call to authenticate a user on Twitter using their OAuth method. I carefully followed the instructions multiple times and this is what I've managed to put together so far. Currently, I am f ...

AngularJS - How to Deactivate List Items

Currently, I am working on developing a breadcrumb navigation system using AngularJS. However, I am facing an issue where some of the links need to be disabled based on certain user requirements not being met. After researching the Angular documentation, ...

Tips for passing a variable containing an image source from Node.js to a Jade file

Below is the code snippet from my index.js file, where I'm using express for routing: var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res){ var db = req.db; ...

Endless loop in React when using history.push and useEffect

I'm relatively new to working with React and I've encountered a dilemma that feels like a chicken-and-egg situation. I want to ensure that a query parameter in the browser URL stays synchronized with a useState variable on the page. However, my i ...

How can you show the default calendar for a specific month and year in a Vue3 datepicker?

I've been utilizing the @vuepic/vue3datepicker component, which automatically shows the days of the current month when integrated in my project: <template> <VueDatePicker v-model="date" inline></VueDatePicker> </templ ...

Activate the Bootstrap modal when the React site fully loads

Is there a way to display a modal with information as soon as a page loads in React? I attempted using the standard method: $(window).on('load',function(){ $('#myModal').modal('show'); }); However, it seems ineffective p ...

Utilizing AJAX in Wordpress to Dynamically Update HREF Links

My website now has AJAX functionality, and you can see a live example at www.mathewhood.com. I am interested in changing the URL format when clicked from To something like , without the /sitefiles/ for security reasons. Below is my code. If anyone is ex ...

Differences between count() and length() methods in Protractor

When it comes to determining the number of elements inside the ElementArrayFinder (which is the result of calling element.all()), you have two options according to the documentation: $$(".myclass").length, detailed here: This approach involves using ...

Generate a complete screenshot of a website using Chrome 59 through code

Is it possible to programmatically capture a full-page screenshot of a website using the latest Chrome 59 and chromedriver with Selenium Webdriver, even if the website is larger than the screen size? ...

Enforce the splicing of the ng-repeat array with the utilization of track by

Our app incorporates a task list that can potentially grow to a substantial size. The main task list is accompanied by a sidebar, where selected tasks can be edited using a different controller (TasksSidebarCtrl instead of TasksCtrl which handles the list ...

Violation of Content Security Policy directive has occurred

During my full-stack project development, I encountered an issue with the inclusion of the bundle.js file in my base HTML file using a simple script tag. When trying to render the page and utilize the JS functionality, I faced a content security policy vio ...

Utilizing jQuery's nextUntil() method to target elements that are not paragraphs

In order to style all paragraphs that directly follow an h2.first element in orange using the nextUntil() method, I need to find a way to target any other HTML tag except for p. <h2 class="first">Lorem ipsum</h2> <p>Lorem ipsum</p> ...