Design a directive for universal use in both models and controllers

Throughout my app, there is a consistent functionality where users can input a title and link.

I decided to create a directive for this. However, the directive needs to be utilized in various controller contexts.

For instance, in the /contracts view, the controller is ContractsController, which sends an API request to save a contract upon submission.

On the other hand, in the /meeting-notes view, the controller is MeetingNotesController, responsible for saving meeting notes against a client through a different endpoint.

Below is the current state of my directive: app.js

.directive('myprefixLinkAttachment', function($timeout) {
    return {
        restrict: 'A',
        templateUrl: '../partials/directives/link-attachment.html',
        scope: {},
        link: function link(scope, element, attrs) {
            $timeout(function() {
                console.log(scope.$parent);
                console.log(scope.title);
            }, 5000);
        }
    }
})

The timeout successfully returns the correct value - I used it to test if I could obtain the value.

link-attachment.html

<md-input-container class="md-block" md-no-float flex="100" flex-gt-xs="66">

    <input ng-model="title" placeholder="Title...">

</md-input-container>

<md-input-container class="md-block" flex="100" flex-gt-xs="33">

    <input ng-model="link" placeholder="Title..." ng-keypress="CtrlNameHere.save($event)">

</md-input-container>

I invoke the directive within the ContractsController, but this may vary:

<div layout="column" layout-gt-xs="row" class="new-entry-line" myprefix-link-attachment>

To sum up, I aim to freely implement the directive while ensuring that the appropriate controller is called to handle the CtrlNameHere.save() method.

Answer №1

It seems like you haven't posed a question yet. I assume you are wondering how to trigger a controller function when using the same directive in different controller scopes.

The solution is to pass the directive the specific function it should execute.

To do this, your directive should have a property called controllerFn that accepts the function:

scope: {
    controllerFn: "="
}

When using the directive, provide it with the desired controller function like this:

<myprefix-link-attachment controller-fn="someControllerFunction">

Finally, in the template, call the function that already exists in the scope:

ng-keypress="controllerFn($event)"

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

Eliminating an ngRepeat item from the $rootScope array does not automatically result in the item being removed from the html code

Attempting to eliminate an li from a ul using angular. Although the element is successfully removed from the array, AngularJS does not remove the li until it is interacted with, such as being hovered over or clicked. See the code below: app.js myApp.run( ...

The login page continues to show an error message for incorrect credentials unless the submit button is clicked

My current project involves a React component called "Signin.js". Within this component, there are login input fields as I am working on creating a login system using Node.js, Express.js, and MySQL. To achieve this, I have set up a post request that sends ...

What is the best way to merge the values of an array within an array of objects with the same property in JavaScript?

Check out the array below: const a = [ { 26: [0], 27: [100], 28: [0] }, { 26: [0], 27: [100], 28: [0] }, { 26: [0], 27: [100], 28: [0] } ] Is there a function available that can merge arrays with identical ...

What is the most effective method for inputting a date/time into a Django view?

Looking to create a feature where users can see what events are happening at a specific time. What is the most efficient method to implement this request? For example, if I want to display all current events, should I submit a post request to /events/2009 ...

Guide on accessing Azure Configuration Application settings in a Node application with JavaScript

Currently, I have a node.js application named "myClient" deployed on Azure as an App Service. Within this setup, I utilize several configuration files that contain specific values tailored to their respective runtime environments: appconfig.json is used f ...

Issue with Javascript/Jquery functionality within a PHP script

I have been attempting to incorporate a multi-select feature (view at http://jsfiddle.net/eUDRV/318/) into my PHP webpage. While I am able to display the table as desired, pressing the buttons to move elements from one side to another does not trigger any ...

Achieving accurate JSON output from Elasticsearch's autosuggest feature can be

Running my node.js server involves sending queries to an elasticsearch instance. I have a JSON example of the query's output: { "took": 2, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 ...

Error: The "checkAvailability" method is not available in the model object

When attempting to implement some functionality methods for my model, I encountered an issue where sending a request resulted in the following traceback: /home/nano/Dev/JS/OMI/node_modules/mongoose/lib/utils.js:413 throw err; ^ TypeE ...

Convert decimal numbers to fixed precision of two decimal places for non-zero decimals

The goal is to achieve two decimal places excluding zeros 1.2234 => 1.22 0.2345 => 0.23 0.02345 => 0.023 (instead of 0.02) 0.0000002345 => 0.00000023 (instead of 0) 0.0000002346545645645646465465 => 0.00000023 (instead of 0) 0.002035 = ...

Rendering user actions instantly in React.js without waiting for server propagation

I am currently developing a shopping list web application where users can toggle items as 'checked' or 'unchecked'. The flow of data in this application is as follows: click on item checkbox --> send database update request --> ...

Steps for choosing an image and embedding it within a div element

Upon loading the site, an image is displayed with the following code: <img id="some_Image" src="some_source"> However, I am looking to avoid requesting this image again from "some_source". This is because calculating the image can be resource-inten ...

Generating a matrix of HTML video elements in p5.js triggers Uncaught TypeError

Struggling to create a 2D array of video objects. It works fine with a regular array, but throws an error when attempting to make it 2D - Uncaught TypeError: Cannot read property 'tv' of undefined. The problem seems to be in this line of code: tv ...

Node.js request.url is returning incomplete URL

I am currently testing out the code snippet provided in a beginner's book on Node.js. var http = require("http"); var url = require("url"); function onRequest(request, response) { console.log("request URL is: " + request.url); var pathName ...

How to retrieve query parameters using Angular 2's HTTP GET method

Seeking assistance on my Ionic 2 app built with Angular 2 and TypeScript. I am familiar with older versions of Angular, but still adjusting to this new environment. I have set up my API with basic query strings (e.g domain.com?state=ca&city=somename) ...

The challenge of maintaining coherence in AngularJS scopes

It's driving me crazy. Our integration with some ATSs involves sending queries and setting variables in the scope upon receiving responses. I always make sure to set the variables within a $scope.$apply() to ensure proper updating. Everything was work ...

What is the best way to modify a variable's value from a nested controller and vice versa?

There seems to be an issue with changing the 'mensaje' variable in both the "padre controller" and the "hijo controller" and visualizing the changes. When clicking on "cambiar padre," the value changes as expected. However, if I then click on "ca ...

Error: Unable to locate http-server command

I am encountering difficulties while attempting to launch an AngularJS project. The http server is refusing to start, even after trying various solutions previously suggested. Upon executing npm list --depth=0, the following error occurred in my project p ...

Working with string interpolation in SQLite3 and Nodejs

Just starting out with this and I'm running into an issue with trying to insert a variable into my sqlite3 query. I keep getting the error { [Error: SQLITE_ERROR: no such column: shmee] errno: 1, code: 'SQLITE_ERROR' } where "shmee" is actua ...

Refresh the page when the parameter in the URL changes

I'm encountering a small issue that I can't seem to resolve. Currently, I am on the following page: http://example.com:8080/#/user/5ad142e8063ebb0537c5343e There is a link on this page that points to the URL below: http://example.com:8080/#/u ...

What is the best way to distinguish between my HTML form submission and my JavaScript form modification process?

I am facing a dilemma with the layout of my form and table on the webpage. The structure is as follows: +-------------------------------------------------+ | FORM | | +------------------------------------------- ...