ElenaDBA ElenaDBA - 23 days ago 8
AngularJS Question

Cannot access form field using AngularJS

I have the following form in my Angular application:

<form id="form1">
<fieldset>
<input type="text" name="field1" ng-model="frm.myID" />
<input type="button" name="btnProcess" class="action-button" value="Process" ng-click="Process()" />
</fieldset>
</form>


In my controller I have:

var frm = this;

$scope.Process = function() {
console.log(frm.myID);

}


frm.myID
comes up as undefined. What am I missing?

Answer

You're not using the object defined on the $scope. Check the below code snippets.

Inside your controller, you seem to be mixing the coding styles i.e. $scope syntax vs. controller aliasing syntax, please go with one approach.

Also please initialize your object to an empty Object i.e. $scope.frm = {};

$scope syntax.

angular
  .module('demo', [])
  .controller('DefaultController', DefaultController);

DefaultController.$inject = ['$scope'];

function DefaultController($scope) {
  $scope.frm = {};

  $scope.Process = function() {
    console.log($scope.frm.myID);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
  <div ng-controller="DefaultController">
    <form id="form1">
      <fieldset>
        <input type="text" name="field1" ng-model="frm.myID" />
        <input type="button" name="btnProcess" class="action-button" value="Process" ng-click="Process()" />
      </fieldset>
    </form>
  </div>
</div>

controller aliasing syntax. You can use $scope in this syntax too but for doing things like setting up watchers, events, etc.

angular
  .module('demo', [])
  .controller('DefaultController', DefaultController);

function DefaultController() {
  var vm = this;
  vm.frm = {};
  vm.process = process;

  function process() {
    console.log(vm.frm.myID);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
  <div ng-controller="DefaultController as ctrl">
    <form id="form1">
      <fieldset>
        <input type="text" name="field1" ng-model="ctrl.frm.myID" />
        <input type="button" name="btnProcess" class="action-button" value="Process" ng-click="ctrl.process()" />
      </fieldset>
    </form>
  </div>
</div>

Comments