Michael Phelps
Michael Phelps

Reputation: 3591

How get form by name in $scope?

How to get form by name in $scope?

Test example:

<div ng-controller="solod">
  <form name="good_f">
   <input type="text" name="super">
  </form>
</div>

<script>
  function solod($scope){
    console.log($scope.good_f) //undefined 
  }
</script>

Is it possible? Thank you

Upvotes: 2

Views: 11835

Answers (3)

Sai
Sai

Reputation: 2068

Another possible way is to use ng-form, this will help you to access the form via scope easily.

<div ng-controller="solod">
  <ng-form name="good_f">
   <input type="text" name="super">
  </ng-form>
</div>

Script code in your controller:

EDIT: As JeremyWeir mentioned, to solve your problem you can use $timeout service of angularjs

 function solod($scope){
    $timeout(function(){
      console.log($scope.good_f);
    });
 }

Upvotes: 4

JeremyWeir
JeremyWeir

Reputation: 24368

You usually don't want the controller to access the form like this, that's coupling the controller to the structure of the view too tightly. Instead, pass the form to the controller like this...

<div ng-controller="solod">
  <form name="good_f" ng-submit="submit(good_f)">
   <input type="text" name="super">
  </form>
</div>



 <script> 
  function solod($scope){
    $scope.submit = function(theForm){
          console.log(theForm)// not undefined 
          console.log($scope.good_f) // will exist now also
    };

    // do stuff in a watch
    $scope.$watch("good_f", function(formVal){ console.log(formVal);});
  }
  </script>

Otherwise, if you just want to track the value of the text input, give it an ng-model

Edit: On further research, $scope will have good_f as a property, just not when you're logging it in the constructor. You could set up a watch on good_f if you wanted, but I still think you should pass it in.

name (optional) string Name of the form. If specified, the form controller will be published into related scope, under this name.

https://docs.angularjs.org/api/ng/directive/form

Upvotes: 6

swapnesh
swapnesh

Reputation: 26732

Caution: Don't use this - seriously

Angular is not jQuery.

As par as your question is concerned you can use $element in your controller(if you are not concrete with the $scope usage for this use case) -

myApp.controller("myCtrl", function($scope, $element){
   alert($element.find('form').attr('name')); 
   $scope.myFormName = $element.find('form').attr('name');
});

PLNKR DEMO

Upvotes: 2

Related Questions