Invoking a function from a parent controller using an Angular directive

I'm trying to make my directive call the parent's controller function. Here is an example of my directive:

HTML:

<div ng-app="myapp" ng-controller="mainController as mainCtrl">
some body text<br>
    <a href="javascript:;" ng-click="mainCtrl.myfunc()">Click Me from body</a>
    <photo photo-src="abc.jpg" caption="This is so Cool" />
</div>

Javascript:

var app = angular.module('myapp',[]);

app.controller('mainController', function(){
    var vm = this;
    vm.myfunc = myfunc;

    function myfunc(){
        console.log("Log from myfunc");
    }
});

app.directive('photo',function(){
    return {
        restrict: 'E',
        template: '<figure> <img ng-src="{{photoSrc}}" width="500px">   <figcaption>{{caption}}</figcaption>    <a href="javascript:;" ng-click="mainCtrl.myfunc()">Click Me</a></figure>',
        replace: true,
        scope: {
            caption: '@', 
            photoSrc: '@'
        }
    }
});

http://jsfiddle.net/7q9v3zz2/

While clicking on Click Me from body link displays the console log message, clicking on Click Me from directive does not trigger any action. How can I resolve this issue?

Answer №1

When working with isolated scope, it's important to note that you cannot directly access the parent scope as they are not inherited. One way around this is to use $parent (such as

ng-click="$parent.mainCtrl.myfunc()"
), but this can lead to messy and tightly-coupled code. Instead, consider using function binding (&).

return {
        restrict: 'E',
        template: '<figure> <img ng-src="{{photoSrc}}" width="500px">   <figcaption>{{caption}}</figcaption>    
        <a href="javascript:;" ng-click="onClick()">Click Me from directive</a></figure>',
        replace: true,
        scope: {
            caption: '@',
            photoSrc: '@',
            onClick: '&' //<-- Accept function binding and use it in the template
        }
    }

Remember to register it at the consumer level to make it more reusable.

 <photo photo-src="abc.jpg" caption="This is so Cool" on-click="mainCtrl.myfunc()" />

Check out the demo on Fiddle

If you prefer, you could also opt for child scope creation instead of isolated scope to directly call the parent controller method. Here's a helpful demo.

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

Ember controller failing to update template upon property set within promise execution

I am facing an issue while integrating user login functionality in my application. After retrieving the user data from the server, I aim to display the user's name on the page once the process is completed. The login form appears as a popup window, in ...

A guide to displaying a loading spinner using a filter in AngularJS

I have implemented a filter to display certain values in a table. These values are fetched using ajax calls and I want to display a spinner while the data is being retrieved. Here's my code snippet: app.filter("fetchedValue", function(){ retu ...

Is it possible for Angular to retrieve information from one JSON file but not another?

After updating the names in the code to reflect the current ones, I would greatly appreciate any help or suggestions! The json file has been provided, so there's not much additional setup required. Just a heads up: I haven't created a service fi ...

Having trouble getting datatables.net to function properly with JavaScript

I've been experimenting with datatables from http://datatables.net/ Attempting to make it work using javascript, but I'm facing issues. Even when following the example provided on the website, it still shows a blank page. Does anyone have any su ...

Is it possible to delete an element from a JSON file by solely utilizing the element's ID?

I'm fairly new to JavaScript and I've tried various online solutions without success. Currently, I'm working on creating a backend for a todo list application where I aim to implement the feature to delete items from the list. Below is the ...

Trouble updating outside controller data while using AngularJS directive inside ng-repeat loop

I am currently working with a isolate scope directive that is being used inside an ng-repeat loop. The loop iterates over an array from the controller of the template provided below: <!DOCTYPE html> <html> <head> <link rel="sty ...

Prevent the propagation of JS events when clicking on a table row

Here is the scenario with an HTML-table: <table> <tr> <td> Row 1 </td> <td> <!-- Hidden JSF-button --> <button class="hide" /> </td> </tr> </table> ...

Count the number of documents in a MongoDB aggregation cursor

After exploring the API documentation, I noticed that cursor.count() function is no longer available. This led me to wonder if there was an alternative way to obtain a count of the aggregate data. My goal is to determine the total number of documents whi ...

"Utilizing Ajax to create a dynamic loop within a div

I'm a beginner in Ajax and I'm working on creating an Ajax call for multiple div elements. Imagine I have a DOM structure like this: <div id="form"> <div id="child_1"> <div id="child_1_select"></div&g ...

How do I retrieve the content within this HTML element using JavaScript based on its ID?

Is there a way to extract the string from this specific HTML element using JavaScript? The element has an id of recItemString_GPLA\|input, and within it, there is a string containing "qty" that I need to retrieve. Upon inspection of the element, the f ...

Identifying Whether Angular ng-repeat is Displaying Output or Not

I am trying to display a "No result" message when the search field does not have any matches. The current filter is working fine, but it does not show the message when there are no results. How can I achieve this? <div class="portfolio-list-wrap" ng-co ...

Determine if the object's value is present

My current JavaScript setup looks like this: var NAMES = []; function INFO(id,first,middle,last){ var newMap = {}; newMap[id] = [first, middle, last]; return newMap ; } Next, I have the following code block: for (var j = 0; j < NUMBER.leng ...

Slider malfunctioning following AJAX loading

After the user clicks on #mail-wrap, I am attempting to trigger the ready event which loads another page with AJAX so that sss() can be refired. Despite my efforts, it seems like it is not working as expected. Can you help me identify what might be going w ...

The specified subpath './lib/tokenize' does not match any defined "exports"

As a newcomer to React, I've been facing some challenges while trying to get started. Despite searching on Google and other platforms, I couldn't find a solution to my problem. I was attempting to run code from a YouTube channel called Lama Dev b ...

Create an HTML table with dynamic columns generated using the ng-repeat directive

Can you assist me in creating an HTML Table using JSON data with Angular ng-repeat? Check out the demo here Here is the JSON Data: { "account": { "accountId": "54545", "premise": { "address": { "address1": "1800 Bishop Gate Boule ...

Guide to retrieve the Last-Modified date using Javascript

It is common knowledge that the document.lastModified function returns a string containing the date and time when the current document was last modified. Is it possible to obtain the Last-Modified for a script? Here is an example of HTML code: ... <s ...

The jQuery click event is failing on the second attempt

My PHP code dynamically generates a list, and I want to be able to delete rows by clicking on them. The code works fine the first time, but not the second time. HTML <li> <div class="pers-left-container"> <img src="<?php ech ...

The getStaticProps function in Next.js does not pass any data back to the pages

After setting up my hosted database, I encountered an issue with fetching data from it. Despite confirming that the database is running smoothly through the Swagger app, no data appears when called via API form. import React from 'react'; export ...

Using Python Selenium to interact with elements on a web browser and make edits

Is there a way to modify an element in a web browser using Python 2.7 Selenium? Consider this element: <span id="some-random-number">100</span> While you can retrieve the text with: driver.find_element_by_id("some-random-number").text how c ...

What are some strategies for creating a website that caters to both web crawlers and users of single page applications?

Let's get down to the specifics. I've got a frontend website at (don't worry, it's not porn). If you have javascript enabled, the URL becomes [this uses jquery/ajax load]. If you're without javascript, the URL remains as . To ...