1

I just answered a question here

How i send value when i click button to server and popup directive

His code looked like this

<div ng-controller="IndexController">
  <label id="number" >5</label>
  <input type="button" ng-click="getUserDetails()" >
</div>

He was trying to access the value of the label element with id #number.

I understand that in Angular, DOM manipulation and querying should be done in a custom directive, and not inside a controller. I therefore gave this solution.

Since you want to access the value of a number, you are interacting with the DOM. The best solution for this is creating custom directives. Here is an example.

angular.module('myApp', [])
    .directive('getValue', function({
        restrict: 'A',
        link: function(scope, elem, attrs) {
            elem.bind("click", function() {
                scope.value = elem.prev().text();
            });

        }
    });

I know that in a directive's link function, you pass in scope, element and attrs as a param. In this line, I'm trying to set a scope variable to the label's value.

scope.value = elem.prev().text();

But I have a suspicion that I'm not doing it correctly. Since directives are the way to go, how can I do this.

I also checked this as a reference

Easiest way to pass an AngularJS scope variable from directive to controller?

I've read about the controller function inside directives, but I need the link function for getting the value from the DOM.

Community
  • 1
  • 1
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
  • The main reason to "limit DOM manipulation to a directive" is to encapsulate changes that angular can't respond to. Reading the value on it's own isn't something that angular needs to respond to. Beyond that, the core problem in the original question can probably be solved proactively by supplying the value on DOM creation instead of reactively trying to divine the value later. I suggested something to that effect in that question as well. – Claies Dec 21 '15 at 01:31

1 Answers1

0

There's no need for a custom directive for that. ng-click can work:

$scope.getUserDetails = function(e){
   $scope.value = e.target.previousElementSibling.innerHTML;
}

HTML

<div ng-controller="IndexController">
  <label id="number" >5</label>
  <input type="button" ng-click="getUserDetails($event)" >
</div>

$event

MinusFour
  • 13,913
  • 3
  • 30
  • 39
  • However, from what I read anything involving the DOM must be done in custom directive – Richard Hamilton Dec 21 '15 at 00:43
  • 1
    You wouldn't gain much from a custom directive IMO. If the `label` was part of the custom directive yes, you are encapsulating part of the DOM in the directive. – MinusFour Dec 21 '15 at 00:45