Retrieve the value of a property in a directive's isolated scope

Is there a way to access the isolated scope's property in the directive tag? Let's take a look at a simplified example:

angular.module('app', [])
    .controller('myController', function() {
        var result_el = document.getElementById("result");
        this.log = function(text) {
            var p = document.createElement("p");
            p.innerHTML = text;
            result_el.appendChild(p);
        }
    })
    .directive('myDirective', function() {
        return {
            restrict: 'E',
            scope: {
                'click_fn': '&myClick'
            },
            template: '<span ng-click="click_fn()">Click me!</span>',
            link: function(scope, element) {
                scope.my_prop = 'text property';
            }
        }
    });
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>

<div ng-app="app" ng-controller="myController as mCtrl">
    <my-directive my-click="mCtrl.log(my_prop)"></my-directive>
</div>
<div id="result"></div>

In this scenario, I am trying to retrieve the my_prop property from the directive's scope. Is there a way to achieve this?

Answer №1

To properly define an isolate scope in a directive, use the Directive Definition Object (DDO) as shown below:

 scope: {
         click_fn: '&myClick' // The click_fn should not be a string 
       },

When working with a directive template, parameters need to be passed in an object literal (aliasing) like this:

Directive template

template: '<span ng-click="click_fn({my_prop:my_prop})">Click me!</span>'

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

AngularJS - Structuring extensive services and functions

When it comes to organizing my services, I find myself struggling to pinpoint the perfect approach. In one of my larger services, there is a method dedicated to validating a substantial object. This method's complexity calls for a more streamlined ap ...

Ways to invoke a JavaScript function linked to an Angular element

Within my angular view page, there is a div with an id that has a click event written in a separate JavaScript file. This JavaScript file is unrelated to the angular application and the function within it never seems to be triggered. How can I manually t ...

Substituting Specific Content on a Webpage

I need to update a specific phone number within a paragraph without accessing the code inside the body myself. It has been provided by our partner and I am unable to modify it directly. If you would like to explore different options, please reach out to ...

Localstorage functionality in Angular 2

I'm currently exploring the usage of localstorage in angular 2 while utilizing angular cli. app.component.ts export class AppComponent implements OnInit { currentItem: string; newTodo: string; todos: any; constructor(){ this ...

What occurs when you use the statement "import someModuleName from someModule" in JavaScript?

When reusing a module in multiple places, you typically use module.exports = yourModuleClassName to make the module exportable. Then, when you want to use it elsewhere, you can simply import it with import yourModuleClassName from 'yourmodulePath&apos ...

Leveraging classes in routing with express framework

After deciding to convert the code from functions to classes, I ran into an issue where 'this' was undefined. Routing // router.js const ExampleController = require('./ExampleController'); const instanceOfExampleController = new Exam ...

Task that merges multiple JSON files into one using Gulp

Within my directory, I have a collection of JSON files that contain arrays of objects. Folder A file1.json file2.json file3.json All the files in this folder have the same structure (a single array containing multiple objects). My goal is to execu ...

JavaScript - Populating Dropdown Menu with Fresh Information

I'm attempting to populate a combobox (input) with data fetched via AJAX. The goal is to display every city associated with a selected state, chosen from another select control (the state control). My Attempt: I've implemented the "change" even ...

AngularJS offers a variety of 'select all' checkboxes tailored for specific lists of checkboxes

Within my webpage, I have three different sets of checkboxes. Each set includes a "select all" checkbox. Instead of repeating code lines, I am implementing a single function with a parameter to select specific checkboxes within each set. $scope.sele ...

Locating all elements on a webpage that are either above or below a specific element, capturing those that intersect visually

Is it possible to locate all the additional HTML elements that a particular element overlaps with, is positioned under, or intersects with? My goal is to ensure that this element is displayed above every other element. I am looking to identify all interse ...

performing dual functions within a single click event handler

Is there a way to simultaneously execute 2 functions? In the following code snippet, I am trying to capture the id of the parent Div with the onclick event and then trigger a function using that id. <div id="selDe"> <input type="radio" class="ger ...

Spinning picture when mouse is clicked

Currently experimenting with the code found at Rotating an element based on cursor position in a separate element and http://jsfiddle.net/JqBZb/ I have rewritten it in its entirety, accessible at the link below, but unfortunately, it's not functionin ...

Discover convenient debugging utilities tailored for Angular JS 1.5

Being a newbie in the world of Angular JS, I may have some simple questions about debugging tools specifically for Angular JS 1.5. ...

Sometimes, Node.js struggles to retrieve values from my configuration file

I'm currently utilizing node.js on the server side with a RESTful service setup as follows; app.get('/getAndroidVersion', function(req,res){res.json({version: config.androidVerion});}); This service is expected to return the version value ...

Looking for assistance in managing arrays and improving axios response handling

I currently have a structure like /url/{category}. Below is the code snippet used to fetch and display some of these on the main page: export default { data() { return { topnews:[], newsfive:[], categories: ...

Remove any actions that a view has linked to the app.vent

By invoking view.unbindAll(), will the events that I registered on the global event bus be removed? ...

Is caching a feature in AngularJS, and are there methods available for disabling it?

var modalInstance = $modal.open({ templateUrl: '/template/edit-modal.html', controller: ModalInstanceCtrl2, resolve: { locations: function () { return locationToEdit; } }, scope: $scope.$new() }); ...

How can I modify the return value of Node.js' REPL from underscore _ to a different symbol?

Another question worth exploring: Utilizing the Underscore module in Node.js Has anyone found a method to customize the variable that Node.js' REPL assigns as the last return value? For instance, altering it from _ to __ or $_ could simplify globaliz ...

custom vertical tab label text not aligning to the right in material-ui with textAlign

I am struggling with customizing the tabs in material-ui to display them vertically. I also want the text labels of these tabs to align to the right for a more cohesive look. Despite trying various styling options, I have not been successful in achieving t ...

Can you explain the concept of injection context within Angular version 16 and later?

I have come across the term "Injection context" and am trying to understand what it entails. In Angular, there are several things that are connected to injection context: EnvironmentInjector#runInContext injectionContext runInInjectionContext inject() Fr ...