Issue
I'm learning Angular I made this and it works fine, it's simple:
<span>Your Name:</span><h1>{{Name.first+' '+Name.second}}</h1>
<script>
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.Name = { first: 'First', second: 'Second' };
})
</script>
But I want the controller to read the values from the text inputs, so I made this:
<p>First Name: <input type="text" ng-model="fName" /></p>
<p>Last Name: <input type="text" ng-model="lName" /></p>
<span>Your Name:</span><h1>{{Name.first+' '+Name.second}}</h1>
<script>
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.Name = { first: $scope.fName, second: $scope.sName };
});
</script>
But it doesn't work, I'm beginner enough to be sure that I made it wrong
Solution
You have to use some event to update your $scope.Name object As you are displaying $scope.name as output.
Currently I have used ng-change you may also use ng-click,etc. as per requirement
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.getName=function(){
$scope.Name = { first: $scope.fName, second: $scope.lName };
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<p>First Name: <input type="text" ng-change="getName()" ng-model="fName" /></p>
<p>Last Name: <input type="text" ng-change="getName()" ng-model="lName" /></p>
<span>Your Name:</span><h1>{{Name.first+ " " +Name.second}}</h1>
</div>
Answered By - J-Mean
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.