I have to get the value of an input text with AngularJS but without using Controller. How i can get this value? I saw this posts but uses .controller link post
-
You can use angular.element: https://docs.angularjs.org/api/ng/function/angular.element – joaumg Jan 13 '16 at 11:35
-
Just curious: why don't you use a controller? – Gabriel Ilharco Jan 13 '16 at 11:36
-
we can not use a controller. project requirements.... – agonzalezmc Jan 13 '16 at 11:46
-
why use angularJS then? – koox00 Jan 13 '16 at 11:53
3 Answers
You can use this code, with angular.element:
angular.element(document.querySelector('#your_input_tag_id')).val();
or, with simple jQuery:
$('#your_input_tag_id').val();

- 1,649
- 1
- 21
- 34
Rather than querying the DOM for elements (which isn't very angular see How do I "think in AngularJS" if I have a jQuery background?) you should perform your DOM manipulation within your directive. The element is available to you in your link function.
So in your myDirective
return {
link: function (scope, element, attr) {
element.html('Hello world');
}
}
If you must perform the query outside of the directive then it would be possible to use querySelectorAll in modern browers
angular.element(document.querySelectorAll("[my-directive]"));
$('#your_input_tag_id').val();
however you would need to use jquery to support IE8 and backwards
angular.element($("[my-directive]"));

- 229
- 1
- 4
- 25
make your input a model and the value will always be available as the model
<input type="text" ng-model="myModelName">
and then your value will be available within the scope of your module as myModelName
console.log('value = ' + $scope.myModelName);
, if you are trying to get the value from somewhere other than the scope of the module or app then you are probably doing it wrong and not the angular way, it really is best to use a controller or link function even if it's the main app controller or link function, and you would be well placed to push back on any requirement not to use a controller (which sounds like a bad or misunderstood requirement).

- 814
- 1
- 7
- 10