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

What is the best way to generate an empty object that mimics the structure of an object within an array of objects in AngularJS

I am facing a scenario where I have an array of objects structured like this: $scope.users = [ { ID: "1", Name: "Hege", Username: "Pege", Password: "hp", }, { ID: "2", Name: "Peter", User ...

Guide to automatically sending users to a subdomain depending on their IP address location

Currently, my website is built using Node Express and I have a specific requirement. I want to redirect users to different subdomains based on their current location. For example, if a user in Singapore accesses site.com, they should be redirected to sg. ...

Explore encoding of array objects into JSON format

I seem to be having trouble retrieving values from array objects. When passing my array of objects from PHP, I use the following syntax initiate_data(".json_encode($my_array)."); To check the array in JavaScript, I have written this code snippet functi ...

Unrecognized OnClick Function in AJAX

As someone who is relatively new to AJAX, I am trying to work on a project that involves fetching data from a route and using AJAX to create a table. Within this table, each row has a button that, when clicked, should trigger a POST request to add some dat ...

Pressing element against another element

I have a somewhat unconventional request - I want to trigger a click event with an HTML element while hovering over another element. Let's imagine we have a .cursor element hovering over an anchor text. In this scenario, clicking on the .cursor shoul ...

Attempting to instruct my chrome extension to execute a click action on a specific element found within the webpage

I am currently working on developing a unique chrome extension that has the capability to download mp3s specifically from hiphopdx. I have discovered a potential solution, where once the play button on the website is clicked, it becomes possible to extract ...

Modify visibility or enable state of a text box according to a checkbox in PHP

Currently, I am utilizing PHP to exhibit a vertical list of numbered checkboxes, with one checkbox for each day in a specific month. Next to every checkbox, there is a text box where users can input optional notes for the selected day. To ensure that users ...

The feature to change location in AngularJS seems to be malfunctioning

Recently diving into the world of Ionic, I've encountered an issue with transitioning between two views in a simple login application: index.html <ion-pane> <ion-header-bar class="bar-stable"> <h1 class="title">Sample Ionic ...

Sending information from popup to primary controller wit the use of AngularJS - (Plunker example provided) with an autocomplete field embedded in the popup

My scenario is a bit unique compared to passing regular data from a modal to the main controller. The input field in my modal has an autocomplete feature. Here is the Plunker I have included for reference: http://plnkr.co/edit/lpcg6pPSbspjkjmpaX1q?p=prev ...

What is the correct way to display the date in a React application?

I am working on a project that involves integrating solidity contracts into a web portal. In one of the contracts, I have stored dates as uint values like this: 1539491531. However, when I display these dates on the web page, they appear different from wh ...

What steps should I take to execute a unique function the very first time a user scrolls to a specific element?

The issue at hand: I am working with a sophisticated looping image carousel that needs to initiate - starting from a specified initial slide - as soon as the user scrolls to a specific division. It must not restart if the user scrolls up or down and then ...

Rendering on the server using react-router v4 and express.js

I've been working on implementing server-side rendering with the latest version of react-router v.4. I found a tutorial that I followed at this link: . However, when I refresh the browser, I encounter the following error: Invariant Violation: React.C ...

What is the method for HTML inline handlers to retrieve the global window object and the variables contained within it?

During my coding test, I encountered an interesting scenario. I had a function called write and used a button with an inline onclick handler to trigger the write() function. function write(text) { alert(text) } <button onclick='write("Some tex ...

Unable to navigate a simulated scrollbar

As someone who is new to web development, I am embarking on the journey of building a UI Grid that can effectively display a large amount of data. My goal is to implement a scrollbar that allows for horizontal scrolling across approximately 1,000,000 data ...

Can anyone guide me on creating a Mapbox map layer using React.js?

I'm currently in the process of creating a polygon layer on top of my Mapbox map using ReactMapboxGL. I have some Mapbox Javascript code that I need to convert into React.js format: map.on('load', function () { map.addLayer({ ...

Is there a way to incorporate a responsive side menu using JQuery or CSS3 that can shift the entire page layout?

Hey there, I'm currently trying to incorporate a responsive side menu into my website using either JQuery or CSS3. What I need is a side menu that will smoothly shift the page content when a link is clicked, and also adds a close button (X) to the men ...

What steps should be taken to fix the sinopia installation error?

While operating on redhat5.9, I encountered an exception related to 'make'. I am curious about what they are trying to create. It seems like it's related to JavaScript. [root@xxxx bin]# npm install -g sinopia --python=/usr/local/clo/ven/pyt ...

Steps to create a function in a .js file that uses ng-show conditions

I am in the process of validating a web page where the user inputs must be alphanumeric, have a maximum length of 45 characters, and be unique. Below is the code snippet I am working with. Is there a way to consolidate these three ng-show conditions into ...

Retrieve the file name from the URL while disregarding the query string

Looking for a way to extract the test.jsp from this URL: http://www.xyz.com/a/test.jsp?a=b&c=d Can anyone provide guidance on how to accomplish this task? ...

Relocating to reveal or conceal item

I am currently working with jQuery and trying to achieve a specific functionality. My goal is to hide and unhide an element, while also focusing on the exposed area once it becomes visible. I have a link #welcomeselect that, when clicked, should reveal t ...