0

I am trying to read ng-model from the controller, however I could not get it work. It says the ng-model is undefined. I tried to apply the solution provided by others to solve this similar problem but I still could not get it work. Maybe because I am doing it wrongly.

I have the following code snippet:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.apply = function() {
    $scope.name = {}
    var firstName = $scope.name.FirstName;
    alert(firstName);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <button ng-click="apply()" type="button">Apply</button>
  Name:
  <input ng-model="name.FirstName">
</div>

However, the alert says the variable "firstName" is undefined after clicking the "apply" button. So I tried to use the following code instead.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.apply = function() {

    var theFirstname = "";
    $scope.name = {
      theFirstname: $scope.name.FirstName
    }

    alert(theFirstname);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <button ng-click="apply()" type="button">Apply</button>
  Name:
  <input ng-model="name.FirstName">
</div>

However, it seems like I am unable to assign $scope.name.FirstName to the variable "theFirstname".

1 Answer 1

3

Move the initialization of name above apply().

By doing this, name.FirstName can be initialized from the Template as name is already defined on scope.

In your case, $scope.name={} is defined in the handler, thus name is undefined by the time when ng-model is attached to the textbox.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  // Define the `name` object
  $scope.name = {};

  $scope.apply = function() {
    var firstName = $scope.name.FirstName;
    console.log(firstName);
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <button ng-click="apply()" type="button">Apply</button>
  Name:
  <input ng-model="name.FirstName">
</div>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.