Using an AngularJS directive to trigger a function with ng-click

Everything is working well with my directive, but I would like to utilize it within ng-click. Unfortunately, the function inside the link is not getting triggered.

Here's the link to the code snippet.

<div ng-app="editer" ng-controller="myCtrl" class="container">
  <div class="parents">
    <div ng-repeat="item in items" class="wrap" sibs>
      <span>{{item.name}}</span>
      <button ng-click="">click</button>
    </div>
  </div>
</div>

JS

function myCtrl($scope) {
  $scope.editedItem = null;

  $scope.items = [{
    name: "item #1",
    thing: "thing 1"
  }, {
    name: "item #2",
    thing: "thing 2"
  }, {
    name: "item #3",
    thing: "thing 3"
  }];

  $scope.show = false; //ignore this line

}

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

editer.directive('sibs', function() {
  return {
    link: function(scope, element, attrs) {
      element.bind('click', function() {
        element.parent().children().addClass('unclicked');
        element.removeClass('unclicked');
      })

      scope.myClick = function() {
        element.parent().children().addClass('unclicked');
        element.removeClass('unclicked');
      }
    },
  }
});

I'm trying to invoke the function in ng-click. You can view the updated version here, where the 'sib' is removed from

div ng-repeat="item in items" class="wrap"
.

 <button ng-click="myClick()">click</button> 

Answer №1

In order to maintain a clean and efficient codebase, it is recommended to refrain from directly manipulating the Document Object Model (DOM) as often done in jQuery.

Angular takes a different approach by allowing data to automatically update the DOM when changes occur (https://docs.angularjs.org/guide/databinding). This eliminates the need for manual adjustments most of the time.

This means that using the link function is usually unnecessary. Instead, you can utilize a controller (as shown in your example) or a directive with a controller (https://docs.angularjs.org/guide/directive).

For demonstration purposes, I have made some slight modifications to your controller and template below.

HTML

<div ng-app="editer" ng-controller="myCtrl" class="container">
  <div class="parents">
    <div ng-repeat="item in items" class="wrap" sibs>
      <span ng-class="{ unclicked: !item.selected }">{{ item.name }}</span>
      <button ng-click="selectItem(item)">click</button>
    </div>
  </div>
</div>

JS

function myCtrl($scope) {

  $scope.items = [...];

  $scope.selectItem = function (item) {

      // reset all the items
      $scope.items.forEach(function (i) {
          i.selected = false;
      });

      // set the new selected item
      item.selected = true;
  }

}

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

Automatic capitalization feature for input fields implemented with AngularJS

I have integrated a directive into my input field to validate a license key against a server-side API. While this functionality works well, I also want the license key to automatically add hyphens and appear in capital letters. For example, when a user in ...

An error with jQuery occurred in the client's post response, resulting in a 400 POST HTTP/1.1 error

I am struggling to identify the issue with my code, especially since I'm not very familiar with jQuery. The goal is to create an HTML form for storing car data based on this template: The source code for the HTML form can be found here. Upon clickin ...

Exploring the functionality of dimensions in d3 parcoords

I am diving into the world of d3 and experimenting with Behold, a simplistic example directly from the website. <script src="http://d3js.org/d3.v3.min.js"></script> <script src="d3.parcoords.js"></script> <link rel="stylesheet" ...

Creating an object with an array of objects as a field in MongoDB: A step-by-step guide

I have a unique schema here: const UniqueExerciseSchema = new Schema({ exerciseTitle: { type: String }, logSet: [{ weight: { type: Number }, sets: { type: Number }, reps: { type: Number }, }], }); After obtaining the da ...

Connecting a string array to the navigation bar

Need Assistance with AngularJS: In my controller, I have a string array that looks like this: var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About&apos ...

Struggling with configuring a 'post' endpoint in an express server problem

My goal is to validate that my client is able to successfully post information to its server. I have configured a specific 'route' on my Express server for this purpose. // server.js this is the server for the PvdEnroll application. // var ex ...

Struggling with jQuery fadeIn and fadeOut in IE8?

I am struggling to understand why my fadeIn, fadeOut, and corner() functions are not working in IE8 on my website at . They were functioning properly before, but now they seem to be broken. Can anyone pinpoint the issue causing this problem? If you click ...

Tips on Moving a Bootstrap Modal Popup with the Arrow Keys on Your Keyboard

This example showcases the integration of Bootstrap's Default Modal Popup with jQuery UI Draggable Function. The JS fiddle link provided below contains the code snippet. $(document).ready(function() { $("#btnTest").click(function() { $(&a ...

Tips for ensuring that divs resize to match the container while preserving their original proportions:

#container { height: 500px; width: 500px; background-color: blue; } #container>div { background-color: rgb(36, 209, 13); height: 100px; } #one { width: 1000px; } #two { width: 800px; } <div id="container"> <div id="one">&l ...

Experiencing a 403 Error while using request-promise to extract price data from a website

My current challenge involves using request-promise to scrape the price of an item from Asos.com. Whenever I try to execute the code provided below, I encounter a 403 error. Could it be possible for this error to occur even though the URL I am attempting t ...

Child object referencing in JavaScript

As I delved into testing Javascript, a curiosity arose regarding the interaction between child and parent objects. Would the parent object dynamically update to reflect changes in the child object's value, or would it remain static at the initial stat ...

PhpStorm 2019.2 introduces Material UI components that have optional props instead of being mandatory

My PhpStorm 2019.2 keeps showing me a notification that the Button component from Material UI needs to have an added href prop because it is required. However, when I refer to the Material UI API, I see something different. Take a look at this screenshot: ...

Encountering an issue with React Redux and Typescript involving the AnyAction error while working on implementing

While integrating redux-persist into my React project, I encountered an error. Previously, Redux was working smoothly, but upon the addition of redux-persist, I started receiving this error message: Types of property 'dispatch' are incompatib ...

Using string replacement for effective search finding: Unleashing the power of substring matching

I have a method that adds an anchor tag for each instance of @something. The anchor tag links to a specific sub URL. Check out the code: private createAnchors(text: string) { return text.replace(/(@[^ @]+)/ig, '<a href="/home/user/$1">$1& ...

Angular JS allows you to easily remove the # symbol from a URL, improving the

I am encountering a problem with the "#" symbol in my angular js website's URL. I need to remove the # from the URL but the method provided isn't working and the site is not displaying properly. Can someone advise me on how to successfully remove ...

Learn how to efficiently handle asynchronous tasks while also defining permissions with the Angular permission library

Currently, I am utilizing the angular-permission library in conjunction with ui-router and satellizer. The state definition for home is as follows. I am verifying the user's authorization status using angular-permission. $stateProvider.state('5 ...

Incorporating the sx attribute into a personalized component

I am currently incorporating MUI v5 along with Gatsby Image in my project. To maintain consistency in my styling syntax throughout the application, I decided to include the sx prop in the GatsbyImage component. This is how I attempted it: <Box compon ...

What is the best way to connect the button value with my ng-model data?

I'm having trouble getting the button value to bind to my ng-model. Any suggestions on how I should approach this? Currently, I am utilizing the datepicker from https://github.com/rajeshwarpatlolla/ionic-datepicker <div class="col"> <labe ...

Combining meanings within a geometric interface

When setting up my routes, I like to include an additional field in the configuration. This is how I do it: app.config([ '$routeProvider', ($routeProvider: ng.route.IRouteProvider) => { $routeProvider ...

Guidelines for linking a promise function to a JSX component

How can we use React components to handle the result of a promise function and map it to JSX components? <Promise on={myFunc}> <Pending> ... </Pending> <Resolved> {(data: any) => ( ... )} ...