Invoking a Controller function from an AngularJS Directive

HTML

angular.element(document.querySelector('#dateControls')).append($compile("<search-date></search-date>")($scope));

Directive

myApp.directive('searchDate', function ($compile, $rootScope,$timeout) {
    var linker = function (scope, element, attrs) {

            var template =  '<button class="btn btn-default" ng-click="dateSearch() id="playbackSearch" search-date">Search</button>';

            element.html(template);
            $compile(element.contents())(scope);

    };
    return {
        restrict: "EA",
        replace: true,
        link: linker
    };
});

Controller

$scope.dateSearch = function(){

    scope.userId = 1;
    myModuleService.getData(userId) //call service
    then(function (data) {
    console.log(data);

    }).catch(function (error) {
        throw error;
    });
};

What is the method to execute the dateSearch() function that was defined in my controller?

Answer №1

One option is to include a controller directly within the directive itself, especially if the myModuleService being used is an external service.

For example:

controller: function($scope, myModuleService) {

    $scope.dateSearch = function() {
        scope.userId = 1;
        myModuleService.getData(userId)
        .then(function(data) {
            console.log(data);
        })
        .catch(function(error) {
            throw error;
        });
    };

}

Alternatively, you could structure your code like this:

var controll = function($scope, myModuleService) {

    $scope.dateSearch = function() {
        scope.userId = 1;
        myModuleService.getData(userId)
        .then(function(data) {
            console.log(data);
        })
        .catch(function(error) {
            throw error;
        });
    };

}

return {
    restrict: "EA",
    replace: true,
    link: linker,
    controller: controll
};

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

How can you access and utilize the inline use of window.location.pathname within a ternary operator in

I need assistance with writing a conditional statement within Angularjs. Specifically, I want to update the page to have aria-current="page" when a tab is clicked. My approach involves checking if the tab's anchor href matches the current window' ...

Can variables in JavaScript clash with input names in HTML?

I have the following code in an HTML file: <input type="..." name="myInput1" /> Then, in a JS file associated with this HTML file, I declare a variable to store the value of that input after it loses focus: var myInput1; Should I be concerned abo ...

How can I prevent AngularJS from re-rendering templates and controllers when navigating to a route with the same data?

Is it possible to prevent the templates for the controllers of a route from re-rendering when changing the route, even if the data remains unchanged? ...

I am looking to display the results table on the same page after submitting a form to filter content. Can you provide guidance on how to achieve this?

Could someone provide guidance on how to approach the coding aspect of my current issue? I have a search form that includes a select form and a text box. Upon submission, a table is generated with results filtered from the form. Should I utilize a sessio ...

"Optimize your website by incorporating lazy loading for images with IntersectionObserver for enhanced performance

How can I use the Intersection Observer to load an H2 tag only when the image is visible on the page? Here is the JavaScript code I currently have: const images = document.querySelectorAll('img[data-src]'); const observer = new IntersectionObser ...

Utilize the function of express

The following code is not behaving as expected: var express = require('express'); var app = express(); app.use(function(req, res, next) { console.log('first statement'); next(); }, function (req, res, next) { console.log('se ...

Using both PHP and jQuery to add a class upon changing the URL

I am struggling to implement sorting functionality on my webpage, as the active class is not being added to the selected sorting option... Check out my code snippet below: <ul class="nav nav-tabs"> <li class="menusel active" name="hlavni" on ...

I am unable to directly access the route using the browser's URL. Is there an alternative solution

When using $locationProvider.html5Mode(true) in AngularJS, I am unable to route directly by typing the URL in the browser. Here is a snippet from AppRouting.js: myApp.config(['$routeProvider', function($routeProvider) { $locationProvider.html ...

How can I increase the fading effect more and more with each call of the event using jQuery's fadeTo()?

I'm currently working on a script that is intended to gradually fade an image from 80% opacity to 1%, but every time I click, it goes straight to the set opacity. How can I make the fading effect continuous? Any help would be appreciated. Here is the ...

"Help needed: My experience with logging into Chrome using Selenium usually results in an automatic logout. Any

Currently, I am delving into the world of Scraping using Python along with Selenium. Desire My goal is to successfully log in to Google and Chrome while utilizing Selenium. However, there are concerns that this activity may be perceived as automation for ...

Ways to Implement a Pop-Up Window Specifically for Internet Explorer

In my asp.net web application, I am utilizing the window.Open method to open a new page in another window. My goal is to ensure that this new window only opens in Internet Explorer, regardless of which browser the user is using such as Chrome or Firefox. ...

The attempt to create the property 'and_ff' on the string 'and_chr 89' has failed

Encountering an issue with a Lambda function, I receive an error that does not occur when running the same code within an Express app. I'm puzzled. Data returned by caniuse.getLatestStableBrowsers(); [ 'and_chr 89', 'and_ff 86& ...

Patience is key when it comes to waiting for a function to finish before moving on to the next step

I'm delving into the world of node js and currently immersing myself in the concepts of promises and async/await. Here's a code snippet I've been experimenting with, but I can't quite figure out how to ensure that the code waits until t ...

Struggling with TypeScript and JsObservable? Let us assist you!

Having previous experience with JSRender, JSViews, and JSObservables, I recently embarked on a new project using TypeScript. Unfortunately, I am struggling to understand how to properly utilize TypeScript in my project, especially when it comes to referenc ...

Divide the inner HTML content to extract text for translation purposes using JavaScript

I am currently developing an application that requires extracting the innerHTML of Body, then extracting the text in a JSON format. This JSON will be used for translation, and the translated JSON will be used as input to recreate the HTML markup with trans ...

Tips for managing CSS/style conflicts in JavaScript/AngularJS applications

I am new to AngularJS and I have a requirement to assign CSS properties to a component at the JavaScript file level. When I debug my code after applying the CSS styles to the component, I can see that all the applied CSS properties are behaving as expected ...

Troubleshooting issue with AngularJS routeParams functionality

Here is the URL I am working with: http://localhost:3000/details/59567bc1de7ddb2d5feff262 I am trying to extract the parameter id 59567bc1de7ddb2d5feff262 However, I am facing an issue where routeParam always shows up as undefined This is my controlle ...

Exploring the methods to access GuildMember roles along with their respective details

const Discord = require('discord.js'); const bot3 = new Discord.Client(); const token3 = 'I am not disclosing my bot's token'; const mark2 = '*info personal' bot3.on('message', msg =>{ let args2 = msg.co ...

Is AngularJS Experiencing Bugs with the Webcam getUserMedia API?

I recently created a webcam directive in AngularJS that utilizes a service. For reference, I followed this example: Surprisingly, the example works perfectly on my tablet, but when I integrate the code into my tablet's Google Chrome browser, it encou ...

What are the applications of client-side libraries within node.js?

Recently, I started exploring node.js and came across npm, which has proven to be quite useful. One thing that caught my attention is the fact that many libraries I have previously used in client-side JavaScript development, such as jquery and d3, can be ...