The challenge of accessing controllerAs variables/objects in AngularJS custom directives

After deciding to refactor my code and move DOM manipulation and functions into directives instead of controllers, I encountered an issue with accessing variables/objects defined using the controllerAs 'this' syntax. Despite trying to use bindToController in order to pass these objects to the directive, they still return as undefined within the 'link' function.

For example, I have a variable 'this.test' defined in the controller, but when attempting to access it in the directive through a console log message, it remains undefined.

Sample snippet from the controller:

app.controller('notificationsController', function($scope, $state, $http, $document, $mdDialog, $filter, $timeout, $mdToast) {

  this.test = 'TEST';

Snippet from the directive:

app.directive('clearNotifications', function($mdDialog, $mdToast, $timeout) {
return {
    controller: 'notificationsController', 
    controllerAs: 'notifications',
    scope: {},
    bindToController: {
        notifications: '=',
        filters: '=',
        test: '@'
    },
    restrict: 'A',
    link: function(scope, element, attrs) {
        element.bind('click', function() {

            console.log('notifications.test string test: ' + notifications.test);

Answer №1

this within a controller behaves differently than controllerAs in a directive. In a directive, you must utilize ctrl or model for binding purposes.

var app = angular.module("app", []);
    
app.controller("notificationsController", function($scope) {
  this.test = "foo!";
})
    
app.directive("clearNotifications", function() {
  return {
    controller: 'notificationsController',
    controllerAs: 'notifications',
    scope: {},
    bindToController: {
      notifications: '=',
      filters: '=',
      test: '@'
    },
    restrict: 'A',
    link: function(scope, element, attrs, ctrl) {
      element.bind('click', function() {
        console.log('notifications.test string test: ' + ctrl.test);
      })
    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <button clear-notifications>clearNotifications</button>
</div>

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

Interactive ajax and php dropdown menu

Hey there, I'm running into a small snag with my dynamic select feature, as mentioned in the title. I am aiming to achieve the following outcome: When a user selects an instrument from the first dropdown menu, the second dropdown menu labeled "Besetzu ...

Ending JavaScript promises

I am currently utilizing the Google JS closure library which can be found at https://developers.google.com/closure/library/ Below is the code snippet that I have: if (endDate >= wap.com.ifx.util.IfxComponentUtil.yyyymmdd(currentDate) && goog.o ...

Issues with Markdown text editor code, table, and list functionalities are causing malfunction

Looking for a solution to use markdown editor for writing blog posts? If you're facing issues with code blocks, list items, tables, etc., not working correctly after publishing your markdown-based posts, while other elements like images, links, and bo ...

What is the best way to create a jQuery object that encapsulates a snapshot of a DOM element?

Recently, I discovered that a JQuery object retains a reference to a DOM object. As the HTML is modified, the context of the JQuery object also changes. However, my concern now is how to log these changes without altering the history records of the JQuer ...

Fetching Results from Promise

Repeatedly, this question has been asked in various forms but I still do not understand: I have a resolved promise with a value. When I console.log this object, everything appears to be functioning correctly. I can see exactly what I want to see. My setu ...

Enabling deep linking with $locationProvider.html5Mode in AngularJS

After activating html5Mode in AngularJS with $locationProvider.html5Mode(true), the navigation appears to be off when arriving on a deeper page within the site. For instance: http://www.site.com When navigating to the root, all links on the site are ...

Button-controlled automated presentation

I have devised a method to create an automatic slideshow using JavaScript. However, I am looking to incorporate manual control buttons as well. After adding manual control code, the slideshow seems to be malfunctioning. The provided code below is used for ...

Tips for transferring selection box data between pages with AngularJS?

My goal is to display the value of an option selected from a drop-down menu in page 1 on page 2. Below is the code I have experimented with so far: App.js: app.controller('mainController', function ($scope) { $scope.sizes = [ { siz ...

Encountering issues while trying to install Java using NPM

Encountering errors when attempting to run the following command to install java dependencies for NPM. NPM install -g java In need of assistance to fix this error. C:\WINDOWS\system32>npm i -g java [email protected] install C:\D ...

Are there any potential methods for converting HTML to PDF within a Cordova Angular JS and UWP app using jQuery? I encountered an error stating that 'blob:ms-appx-web' is not permitted to load

view image here I encountered this issue: SEC7134: Resource 'blob:ms-appx-web://mysiteurl/3d5c0f51-04e2-4944-bf3e-4ea19185511c' not allowed to load If anyone has a solution, please help us in resolving this problem. Below is my code snippet ...

What is the best way to showcase the information from this API on an HTML page using Vanilla JavaScript?

I am currently working on implementing an AJAX call to fetch data from a movie API online. Below is the HTML code I have written for this: <html> <head> <meta charset=utf-8> <title>Movie Database</title> ...

Is there a way to import TypeScript modules from node_modules using browserify?

After successfully running tsc, I am facing difficulty understanding how to import TypeScript modules from node modules. The crucial section of my gulp file is as follows: gulp.task('compile-ts', ['clean'], function(){ var sourceTsF ...

What is the best method for expanding the width of a <rect> element with animateTransform?

How can I make a <rect> in SVG expand its width using animateTransform based on a specified value? Additionally, I want the color of the <rect> to change according to the following conditions: If the <rect> value is between 0 and 29: {f ...

Use the filter method to organize arrays into subarrays based on their length, filtering out those with a length greater than or

Hey there, I've been working on incorporating the array filter property to separate subarrays that are greater than and less than 3 into two distinct functions. Unfortunately, I'm a bit stuck on how to continue fixing my functions. Can someone pr ...

I am trying to showcase a collection of images on my homepage, but unfortunately, it is not functioning as expected

Does anyone know how to display images using Angular? I am currently utilizing the pic controller in an AngularJS file. Any assistance would be greatly appreciated. HTML CODE <!DOCTYPE html> <html> <head> <meta charset="utf-8"& ...

Click the button to insert a time stamp into the text area

Whenever the id=dodaj_godzine_button is clicked, I would like to add the current time to id=formularz_wpis_tresc (as a string). I attempted to do this using the code below, but it seems to be malfunctioning. $("#dodaj_godzine_button").click(function(){ ...

Sending an Angular $http post request to a MVC action but the parameter is coming through as

After posting this content: $http.post(Common.blog.save, { blog: blog }) .then(saveBlogComplete) .catch(function(message) { }); The Fiddler output I receive is as follows: {"blog":{"title":"Chicken Is Good","content":"#Chicken Is Good\ ...

Utilize an external JavaScript file function within an AngularJS controller

I have an external JavaScript file with additional functions that I am trying to call from an Angular controller. Here is an example of the external.js file: ... ... function fun() { ... ... } ... ... The controller in question is called acccountCon ...

Hide button for the last input form to dynamically remove in jQuery

At first, I hide the remove button when there is only one form. However, if there are multiple forms and the user deletes all of them, I want the last form to remain visible and not be deleted. Can someone assist with this issue? Here is my code: <! ...

Exploring the Interaction of Users with HTML Table Cell <td>

I am currently analyzing the code for a web page. Within this code, users have the ability to double-click on a cell in a table (<td> as shown below) and input a value. Is there a specific attribute or element within this HTML that indicates user in ...