Invoke the functions of a directive's controller externally

A custom directive is being developed to implement tab functionality using the latest version of AngularJS (v1). The directive includes a controller that exposes an API to child directives, with isolated scopes in all directives:

Parent Directive

scope: {},
controller: function($scope) {
   $scope.values = [];

   this.addValue = function(value) {
        $scope.values.push(value);
   }
}

Child Directive within the link function

scope: {},
transclude: true,
template: '<div ng-transclude></div>',
replace: true,
link: function(scope, element, attr, parentCtrl)
{
    parentCtrl.addValues('test')
}

The child directive contains a custom HTML with its own controller: TestCtrl

function TestCtrl($scope){
    var vm = this;
    ... other logic
}

Implementation

<parent>
   <child>
      <div ng-controller="TestCtrl as t">
          <button ng-click="addValues('new_test')"></button>
      </div>
   </child>
</parent>

The goal is to call the "addValues" method from inside the directive's controller when the button is clicked.

How should the code be organized to achieve this?

Answer №1

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

app.controller('mainCtrl', function ($scope) {
    $scope.message = function () {
        console.log('Button clicked');
    }
});

app.component('childComponent', {
    template: '<button type="button" data-ng-click="$ctrl.clickAction()">Click here</button>',
    controller: myCtrl,
    bindings: {
        onClick: '&'
    }
});

function myCtrl() {
    var control = this;
    control.clickAction = function () {
        this.onClick();
    }
}
<html>

<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
</head>
<body data-ng-app="myApp">

    <div data-ng-controller="mainCtrl">
        <childComponent data-on-click="message()"></childComponent>
    </div>
</body>
</html>

This is just a sample code snippet. Here you can find more information. Hope this explanation helps.

You may also find it beneficial to explore Angular's best practices here

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

Retrieve data from TypeScript file (.ts) and use it in an HTML document

Recently I started learning Typescript and HTML as I work on building an Angular2 application. At the moment, I have a TypeScript file that resembles the following structure: import {Http, Headers} from 'angular2/http'; import {Component} from & ...

Express Js: Implementing Dynamic Data Loading on Scroll

We are currently facing an issue where the dynamic data from Mongo db is loading all at once instead of through scrolling. Our objective is to have the data load progressively as we scroll, all on one single page. // We attempted using Lazy loading carous ...

Utilizing the power of JQuery's delegate method within a gridded

Recently, I encountered an issue with using the delegate method on a grid that is wrapped with the DataTables.Net plug-in. Initially, I had a piece of code that functioned as expected: $("#myGrid tbody tr").click(function() { var id = ...

implementing a three-tiered nested URL structure in Angular

My app.js code snippet: .state('dashboard', { url: '/dashboard', templateUrl : 'resources/components/dashboard/dashboard.html', controller : 'dashboardController', }) ...

Modifying properties within a Vue component instance for unit testing purposes

I am getting ready to test a specific behavior in a Vue component that only occurs when the props are changed. The Vue component I'm working with looks similar to this example, and the key logic for the test is contained within the watcher. <scrip ...

What is the process for transmitting information via a Link in Next.js?

In my upcoming 13.1.5 version, I am faced with a challenge of sending the value of contact.name through a Link in my component. I am looking for the most effective approach to achieve this. The initial code block for the Link represents my original code. ...

Next.js, Knex, and SWR: Unusual issue disrupting queries

When making API requests using Next API routes and interacting with Knex + MySQL, along with utilizing React and SWR for data fetching, I encountered a strange issue. If a request fails, my SQL queries start to append ", *" to the "select" statement, causi ...

Passport.authenticate() fails to redirect users to the desired destination

I am encountering an issue with the passport middleware while trying to authenticate a user. The redirection doesn't seem to be working and I'm unsure what the problem is. Here is the code snippet from the project, and the complete project is av ...

What is the latest method for email delivery using AWS SES?

Seeking guidance on the most current method for sending emails using AWS SES. I'm encountering difficulties finding updated information, and my configuration file seems to be outdated. const client = new aws.SES({ region: "eu-west-1", ap ...

Using jQuery to retrieve individual sentences from a paragraph

I'm facing a challenge trying to identify the two shortest sentences from a collection of paragraphs. The structure of the paragraphs is as follows: <p class="some_paragraph">This is a sentence. Here comes another sentence. A third sentence.< ...

Using jQuery to select and print the initial object from an array with multiple identical objects

I have a dataset structured as follows: var json.result= [ {"id":"0","category":"Camera","name":"600D Kit", "condition":"OK"}, {"id":"1","category":"Camera","name":"600D Kit", "condition":"missing cap"}, {"id":"2","category":"Camera","name":"7 ...

jQuery autocomplete feature fails to retrieve suggestions from local text file

I have implemented the code from a Plunker example in an attempt to minimize the number of ajax requests made to the database. The JSON data is being generated correctly and stored in a text file. However, when I try to display autocomplete options, only ...

What is the best way to transmit information from an external PHP file linked to an external database to the content-script.js of my extension?

Currently, I am working on an extension that is designed to extract DOMs from a specific website (not one that I own) and automate a button click while populating certain input fields. The values for the input fields are retrieved from a database that I h ...

Guide on accessing JSON data within a script tag with jQuery through a bookmarklet

Currently, I am developing a bookmarklet that injects jQuery and attempts to retrieve specific data from a webpage that is built using AngularJS. The JSON data required can be found within a script tag when inspecting the page source in Chrome. <script ...

Is there a way to ensure that a popup is scaled in proportion to its content?

Is there a way to make external links open in a new window with a size relative to the parent window, making it clear to the user? I initially used the target attribute but found a workaround like this: <a href="http://example.org" onclick="window.op ...

What is the best way to modify just a portion of the state in React?

Consider the following State object: const initialState = { data: { user: '', token: '', } } In the Reducer function: case 'DO_SOMETHING': return {...state, data: action.payload } If I make a shallow copy of th ...

Challenges with JavaScript arrays object

I am new to JavaScript and struggling with how to extract data from this array. Can you confirm if it is formatted correctly? Shown below is the console output of the array object: [] 0: Item {id: 0, symbol: "VBIV", boughtDate: "2018-07-22", company: "V ...

What causes isomorphic-style-loader to generate a TypeError: Cannot read property 'apply' of undefined when utilized alongside CSS-Modules?

Currently, I am working on server-side rendering the application, and while the HTML and JS are loading fine, I have encountered an issue with my styles (.less | .scss) not being loaded. After some research, I believe that the problem lies in missing the i ...

Executing a function within setInterval in useEffect is a common practice in JavaScript programming

Is there a way to call a function within the setInterval function of the useEffect hook? useEffect(() => { const timeoutId = setInterval(() => {getTime}, 1000); // this is Line 8 return function cleanup() { clearTimeout(time ...

Comparison between running LESS on the server-side and on the client-side

Can you outline the benefits and drawbacks of implementing the LESS framework on the client-side as opposed to the server-side? Also, is there a negative impact on page load time when utilizing it in a client-side environment? ...