Mosh Feu
Mosh Feu

Reputation: 29347

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>

Upvotes: 4

Views: 15898

Answers (3)

wrivas
wrivas

Reputation: 509

An easy way to do this is using the jQuery little version that comes with AngularJS.

Try this:

var element = angular.element('[ng-model="YOUR_MODEL_NAME_HERE"]');
element.blur(); // element is a jQuery object

This should work

Upvotes: 4

AlexCode
AlexCode

Reputation: 4123

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.

Upvotes: 6

Vincent
Vincent

Reputation: 5445

The reason this is not possible is that this is not something you'll usually want to do in Angular - you're most likely still "thinking like you're using jQuery". Please elaborate on why you want to manipulate the DOM yourself in the first place. Most likely it's a different problem that you can solve with e.g. a directive.

(This may sound like a lame answer, but "don't do this" very likely is the only correct way to handle this situation.)

Upvotes: 2

Related Questions