Answer the question
In order to leave comments, you need to log in
How to pass data from input to controller?
Good evening, there is a controller that makes a Post request to the server
app.controller('PostReq', function ($scope, $http) {
$scope.sendReq = function(name, color, age){
alert(name);
var intAge = parseInt(age);
$http({method: 'POST',
url: 'http://127.0.0.1:8000/api/cat/',
data: {name: name, color: color, age: intAge}
});
}});
<div layout-gt-sm="row" ng-controller="PostReq">
<md-input-container flex ng-model="catName">
<label>Name</label>
<input type="text"/>
</md-input-container>
<md-input-container flex ng-model="catColor">
<label>Color</label>
<input type="text"/>
</md-input-container>
<md-input-container flex ng-model="catAge">
<label>Age</label>
<input type="text"/>
</md-input-container>
<md-button class="md-raised md-warn" ng-click="sendReq(catName, catColor, catAge)">Create cat</md-button>
</div>
Answer the question
In order to leave comments, you need to log in
In general, you need to write ng-model in the input tag and not in md-input-container,
use ng-controller="PostReq as pr" so that the scope is local and not global, then all variables with pr.***** will be exactly local to the PostReq controller.
<div layout-gt-sm="row" ng-controller="PostReq as pr">
<md-input-container flex>
<label>Name</label>
<input type="text" ng-model="pr.catName"/>
</md-input-container>
<md-input-container flex >
<label>Color</label>
<input type="text" ng-model="pr.catColor"/>
</md-input-container>
<md-input-container flex >
<label>Age</label>
<input type="text" ng-model="pr.catAge"/>
</md-input-container>
<md-button class="md-raised md-warn" ng-click="pr.sendReq()">Create cat</md-button>
</div>
app.controller('PostReq', function ($scope, $http) {
$scope.sendReq = function() {
alert( $scope.catName);
var intAge = parseInt($scope.catAge);
$http({method: 'POST',
url: 'http://127.0.0.1:8000/api/cat/',
data: {name: $scope.catName, color: $scope.catColor, age: intAge}
});
}});
I'm a beginner myself and I don't use md-input-container, instead I write ng-model (two-way binding) to the input and the entered data is available in the controller in $scope. For example, $scope.catName. That is, by clicking on the button, you can immediately take data from $scope in the controller.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question