How can the data controller of a model be accessed within a directive that has been defined with "this"?

I'm struggling with accessing data using a directive, especially when I have defined my models like this:

vm = this;
vm.myModel = "hello";

Here is an example of my directive:

function mySelectedAccount(){
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          element.on('click', function() {
            console.log(scope.myModel);                
          });
        }
      }
    }

Because I'm not using $scope, how can I access the "myModel" defined inside my controller within the directive? When trying to access it using the scope parameter in my directive, I receive undefined.

Thank you for your assistance

Answer №1

In this scenario, the variable vm is used to reference the controller instance. Within the scope, the controller context is registered with the vm variable.

Therefore, you can implement the following:

Controller

(function(){

function Controller($scope) {

  var vm = this;
  vm.myModel = 'toto';

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

Directive

(function(){

  function directive() {
    return {
      link:function(scope, element, attrs){
        element.on('click', function() {
          //Accessing vm property within the scope
          console.log(scope.vm.myModel);
        });
      }
    };
  }

angular
  .module('app')
  .directive('directive', directive);

})();

Then, in your HTML, you can utilize the controllerAs syntax:

HTML

<body ng-app='app' ng-controller="ctrl as vm">
  <div directive>{{vm.myModel}}</div>
</body>

You can observe the functionality in action in this Working Plunker

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

Obtain the file path and store it in a variable right after using fs.writefile

Can anyone assist me in obtaining the file path of the created file in the following code snippet? I am passing a barcodeSourceNumber as a parameter and expecting the file path as the return value. pathToFile = generateBarcodeImage('123456789'); ...

Tips for converting file byte code to file form data

From one folder I am retrieving a file and uploading it to another server. However, when I extract the file from the first folder, I receive a byte code representation of that file. The API for uploading the file to the second folder requires FormData as a ...

What are the steps to transform my database object into the Material UI Table structure?

I have a MongoDB data array of objects stored in products. The material design format for creating data rows is as follows: const rows = [ createData('Rice', 305, 3.7, 67, 4.3), createData('Beans', 452, 25.0, 51, 4.9), createData ...

Add a third-party library file to Visual Studio

I'm currently working in Visual Studios and attempting to utilize the library provided at . However, I am encountering difficulties when trying to import the library. I have added the file to the project and attempted to use it within the Book.js (Vi ...

Angular - There is already an ongoing $apply process in place

I am seeking advice on an angular issue: Encountered the same error as outlined here: https://github.com/angular-ui/bootstrap/issues/516. Does this error ("$apply already in progress") pose a risk to my app? My tests indicate that the error does not nega ...

Having trouble using the elementIsNotVisible method in Selenium WebDriver with JavaScript

I'm struggling to detect the absence of an element using the elementIsNotVisible condition in the Selenium JavaScript Webdriver. This condition requires a webdriver.WebElement object, which is problematic because the element may have already disappear ...

What is the best way to display a unique image in a div based on the size of the

Being new to web design, I have a question about creating a webpage with a large image in the center like on GitHub's Windows page. How can I work with the image inside that particular div or area based on different screen sizes? Is it possible to mak ...

Tips for efficiently displaying a computed property on a template using Vuetify?

I am attempting to display only the initials of a user who is logged in while inside a store. Here is my template: <v-menu v-if="this.$store.getters.getLoggedUser"> <template v-slot:activator="{ on, attrs, userInitials }&quo ...

Assigning objects in Vue.js methods

I am working on a Vue component where I need to select a specific value from an array of objects and then copy certain fields from that value into Vue data. <div class="container"> <h4>Add Item</h4> <form @submit.prevent="ad ...

Is it impossible to access the length property of an undefined variable?

After developing a function that calculates the length of a string entered into an HTML textbox, I encountered an error when trying to display the result in another textbox. The function is designed to get the value from the 5th textbox on my HTML page and ...

Encountering a Selection Issue with IE8

I am encountering an issue with my script that involves a form with two select elements for region and state, allowing users to filter states based on the selected region. Everything works smoothly except for one problem - when testing in IE8, I receive th ...

How do I view a wildcard in my ID selector using jQuery?

When I want to initially hide various content scattered around the page, I usually use the following jQuery code: $('#objective_details, #time_estimate_details, #team_members_details, #resources_details').hide(); Is there a method to utilize a ...

I am facing an issue where the PHP header redirection stops working after implementing event.preventDefault() on form submission

After successfully implementing jQuery in my signup page to handle and check the form fields, I encountered an issue where the header("location: ../****.php") no longer redirected me to another page upon clicking submit. Instead, it loaded the new page on ...

Avoiding Memory Leaks and Managing JS Heap Size While Polling Large Amounts of Data Every 5 Seconds with Vuex

I'm currently working on a Vue application that utilizes Vuex for state management. Within this application, I have several store modules set up at the root level. Periodically, every 5 seconds, I retrieve a large amount of data and update the store s ...

Enhance chat functionality by integrating MySQL database to store and update chat messages

I'm currently working on developing a chat system that allows users to enter the chat and send messages. The messages are being stored in a MySQL database, and here is a snippet of my code... <script> $('input[type=text]').on('ke ...

What are effective strategies for safeguarding my AngularJS application code, particularly from unauthorized access through the browser's source code?

I am currently working on an AngularJS application. I have encountered a challenge where the end user is able to view the app code from the browser's source code. I am seeking advice on how to address this issue effectively. Is there any recommended ...

Looking for assistance in creating an html page with a rotating CSS div containing unordered lists and list items

I am sharing the HTML content of my test page that I am looking to customize similar to some websites I have come across. My goal is to create a rotating div with an unordered list (ul li), where only three divs are displayed at a time while the rest remai ...

Using httpRequest to handle binary data in JavaScript

Having trouble deciphering the response of an http request that is a binary datastream representing a jpeg image, despite numerous attempts. Edit: Including the full code snippet below: xmlhttp = false; /*@cc_on@*/ /*@if (@_jscript_versio ...

Using Knockoutjs to fetch and display server-side data within the MVC framework

My goal is to initialize my knockoutjs viewmodel with data from the server. In my ASP.Net MVC project, I achieve this by passing a mvc viewmodel to the view: public ActionResult Edit(int cvId) { CV cv = repository.FindCV(cvId); //auto mapper mapp ...

When the mouse drags across the empty space, the force graph continually jumps

I have some questions. I utilized a force graph and added zoom functionality to it. However, when I drag the mouse over the blank area, the force graph keeps jumping erratically. like this Is there a way to prevent the graph from jumping? Thank you. ( ...