简体   繁体   中英

AngularJS - Setting a controller's $scope variable in a custom directive that accesses the DOM

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM