Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from HTML input element from Angularjs controller

Tags:

angularjs

I'm trying to get the value from an HTML element from Angular controller.

   <div ng-app="myApp" ng-controller="myControler">
<br />

<input id="Text1" type="text"  runat="server" value="aValue" /

My controller :

var myApp = angular.module('myApp', []);


myApp.controller("myControler", function ($scope, $document) {

    var name = angular.element($('#Text1')).val();
     console.log(name);

});

But name returns "undefined"...

Please, what I'm doing wrong ?

like image 778
GCoe Avatar asked Jul 12 '15 01:07

GCoe


Video Answer


3 Answers

angular.element is an alias for jquery $.

You could access that element like this: angular.element('#Text1').val();

ng-model is the angular way to do this though. You can set the value from ASP using ng-init

<input id="Text1" type="text"  runat="server" ng-model="inputVal" ng-init="inputVal='aVal'">

And this can be accessed from the controller using the scope console.log($scope.inputVal);

JSfiddle example: http://jsfiddle.net/n1oppeu2/

like image 189
Preston Van Loon Avatar answered Sep 29 '22 01:09

Preston Van Loon


Why you need angular element to access form element ??

You can get and set value by binding model to it

like this

<input id="Text1" type="text"  runat="server" ng-model="input.field1" />

controller

$scope.input={
  field1:''
}
like image 20
Anik Islam Abhi Avatar answered Sep 29 '22 02:09

Anik Islam Abhi


Using angular element selector #

<input id="Text1" type="text"  runat="server" value="aValue" />

console.log(angular.element('#Text1').val());

or

console.log(angular.element('#Text1')[0].value);
like image 37
Pandi_Snkl Avatar answered Sep 29 '22 01:09

Pandi_Snkl