Ad

AngularJS - Setting A Controller's $scope Variable In A Custom Directive That Accesses The DOM

- 1 answer

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.

Ad

Answer

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

Ad
source: stackoverflow.com
Ad