Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get node element by model property angularjs

There is a way to get the input that binding a model's property.

I want to do this to blur the search input after I send the form, and I want to do this dynamically for later changes in html source.

Example:

var app = angular.module("MyApp", []);

app.controller('ctrl', function($scope) {
  $scope.term = 'test';
  $scope.submit = function(){
    document.querySelector('#search').blur();
    // I want replace document.querySelector('#search') with something like 'getElementByProp($scope.term)'
  };
});
<!DOCTYPE html>
<html data-ng-app="MyApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<div data-ng-controller="ctrl">
  <form data-ng-submit="submit()">
  <input id="search" type="search" data-ng-model="term" />
  </form>
  </div>
</body>
</html>
like image 473
Mosh Feu Avatar asked Dec 14 '22 17:12

Mosh Feu


1 Answers

There's a fundamental error in your intention here.

Please keep the following always in mind: The controller should know absolutely nothing about the DOM

This is a precious rule of thumb that will help you a lot.

Now, of course you need to interact with the DOM from your javascript (AngularJS code), and for that you should use Directives.

In your case though I would use another approach:

if (document.activeElement) {
  document.activeElement.blur();
} 

This will work for any focused elements and you won't need to specifically query any DOM element. So in theory you're not giving the controller any knowledge about the DOM, so for me this doesn't break the rule I mentioned above.

Just as a side note, $document for some reaon doesn't expose this activeElement. I don't have time to dig into the code to see why but as far as I've tested you need to stick with the native document object.

like image 146
AlexCode Avatar answered Dec 29 '22 20:12

AlexCode