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".