Combining inheritance and isolated scopes: a comprehensive guide

I've encountered a situation where I need to sort an HTML table. Here is the code snippet:

<table>
    <thead>
        <tr>
            <th custom-sort-one order="'Name'" >Name</th>               
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Name_AAA</td>               
        </tr>           
    </tbody>
</table>

To tackle this, I decided to create a custom directive called customSortOne.

app.directive("customSortOne", function() {
  return {
    restrict: 'A',
    transclude: true,
    scope: {
      order: '='
    },
    template: '<a href="#" ng-click="sort_by(order)" style="color: #555555;"><span ng-transclude></span></a>',
    link: function(scope) {
      scope.sort_by = function(ColumnToSort) {
        console.log("ColumnToSort =", ColumnToSort);
        scope.TestFunction();
      };
    }
  }
});

The directive works when the user clicks on the Name column header, but there's an issue - it can't access the parent scope's function written in the controller.

To overcome this limitation, I modified my directive using inherited scope.

app.directive("customSortTwo", function() {
  return {
    restrict: 'A',
    transclude: true,
    scope: true,
    template: '<a href="#" ng-click="sort_by(order)" style="color: #555555;"><span ng-transclude></span></a>',
    link: function(scope) {
      scope.sort_by = function(ColumnToSort) {
        console.log("ColumnToSort =", ColumnToSort);
        scope.TestFunction();
      };
    }
  }
});

Now I can access the parent scope, but a new problem arises - I am unable to pass arguments to the sort_by function.

Plunker

Answer №1

If you need to make adjustments to your link function, it's quite simple.

The link function has several parameters such as scope, element, attributes, and more.

Therefore, all you have to do is access the value of the required attribute:

link: function (scope,elem, attrs) {
    scope.order = attrs.order; 

This method works for static attribute values, so quotation marks are not necessary in this case.
Check out the Updated Plunkr here

UPDATE: In regards to the first function: you are able to call a function from the parent scope by passing it like this:

<th custom-sort-one order="'Name'" func="TestFunction()" >Name</th> 

Then in the directive, make use of the & symbol

& or &attr - allows the execution of an expression within the parent scope context.

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

What is the best way to apply ng-repeat to loop through internal HTML elements and content?

I need to iterate through a list and apply different HTML based on certain conditions. If I write the code like this: <ul ng-repeat="item in items"> <li ng-if="item == '1'"> <div><span> <span>My test 123< ...

What's the best approach to retrieve JSON data within an AngularJS controller?

https://jsonplaceholder.typicode.com/posts I need to retrieve information from this URL and showcase it on the browser. In my JavaScript code, I typically perform this task by utilizing XMLHttpRequest and parsing the received data with JSON.parse(respons ...

We encountered a problem while trying to create the route "/": Minification of HTML failed in Nuxt js

After successfully developing a Nuxt app that runs perfectly with "npm run dev," I encountered an error when generating the site using "npx nuxt generate." Despite my efforts, I cannot locate the source of the error. Any assistance would be greatly appre ...

In what way can I decipher a section of the URL query string within my AngularJS application?

Here is a snippet of code that I am working with: var search = $location.search(); if (angular.isDefined(search.load) && search.load != null) { if (search.load = "confirmEmail") authService.confirmEmailUserId = search.userI ...

Using Stringify to modify the value of a particular array in Local Storage

Uncertain of the accuracy of my question, but I am attempting to modify a value within a localstorage array. This is what my localstorage currently contains: [{"id":"item-1","href":"google.com","icon":"google.com"}, {"id":"item-2","href":"youtube.com","i ...

What is the method to assign multiple values to ng-disabled in AngularJS?

Is there a way to assign multiple values for ng-disabled in AngularJS? The issue I'm facing is demonstrated in the following JS Fiddle: http://jsfiddle.net/FJf4v/10/ <div ng-app> <div ng-controller="myCnt"> <h3>A ->> ...

Angular does not automatically update the template

I've been grappling with this issue for quite some time now and I can't seem to figure out why the angular template is failing to refresh when the scope changes. Here's a link to my JSFiddle - http://jsfiddle.net/HB7LU/2591/ (please note tha ...

What method can I use in pure Javascript to identify which day the week begins on, either Monday or Sunday, based on the

Can someone help me determine the start day of the week in local time using only Javascript? The start day could be Monday, Sunday, Saturday, or Friday. I came across this helpful resource on Stack Overflow: <firstDay day="mon" territories="001 AD AI ...

While attempting to retrieve images from S3 using the AWS-SDK Nodejs, users may experience issues with downloading

My goal is to retrieve images from AWS S3 using the AWS-SDK for Node.js. Although the file is successfully downloaded and its size appears correct, it seems to be corrupted and displays a Decompression error in IDAT. async download(accessKeyId, secretAcce ...

"The Promise in the AngularJS Karma test specification did not resolve and the .then() method was not invoked

An issue arises when attempting to perform AngularJS Karma Unit Testing on a service. The service includes a method like the one below: service.getIntersectingElements = function (element, elements) { var deferred = $q.defer(); var tolerance = 20 ...

TypeError thrown by Mapbox markers

Looking to incorporate markers into my map using Mapbox. Below is the Angular TypeScript code I am working with: export class MappViewComponent implements OnInit { map: mapboxgl.Map; lat = 41.1293; lng = -8.4464; style = "mapbox://styles/mapb ...

This function does not have the capability to save cookies

I am attempting to create and retrieve a cookie using JavaScript. Despite running the code below in Google Chrome, the cookie does not persist after page reload. Here is my code: <html> <title> Cookies </title> <b ...

Wait for all animations to complete before changing routes in Angular

I am attempting to postpone a route update until all animations have completed. By iterating through the elements and applying a class with a CSS animation, I am encountering an issue where it only waits for the first animation to finish before proceeding. ...

Is there a way in React JS to attempt a function multiple times using try/catch?

I wrote a function with try catch inside where I make a call to an API for a response. The response returns a Result object with some data. Occasionally, I need to retry the function if certain conditions are met, such as having no name but having a bundle ...

The react-native-video-controls package was used in React Native. When the onBack event was triggered, it successfully navigated back to the initial screen. However, upon returning

https://i.stack.imgur.com/GsS3d.png https://i.stack.imgur.com/HYBOU.png Attached are screenshots showing the issue I am experiencing with my video player. When I click the back button, the screen does not return to its initial state and the flatlist items ...

Despite having a result, the Promise is returning an undefined value

In Vuejs, I have a method named getUsers that takes an array as input and fetches user data from the database. When calling it like this, it successfully returns the results: this.getUsers(executives).then( result => { this.speci ...

Having trouble with the dropdown multiselect feature in AngularJS?

I'm striving to develop a straightforward multi-select dropdown utilizing angular JS, bootstrap, and JS. This dropdown should display days (mon, tue...sun), with options for select all and unselect all. My goal is to create a controller that will de- ...

Encountering silence: React JS fetch call left unanswered by Sinatra server

Exploring the realms of Sinatra and React JS, I am venturing into making a GET call from my React website to a Sinatra server in order to display plain text. The Sinatra Server script: require 'sinatra' set :root, 'lib/app' before d ...

blending javascript and php variables within ajax requests

I am working on a simple jQuery ajax feature, where I need to combine form data retrieved by JS with some PHP variables and send them all through ajax GET method. Here's what I have: var longform = $("input:text").serialize(); $.ajax({ url: & ...

Setting up Angular-CLI on a Windows 10 system

I encountered some challenges while trying to install angular-cli on my Windows 10 system. The issues revolved around Python dependencies and node-gyp, manifesting in error messages similar to the following: ><a href="/cdn-cgi/l/email-protection" ...