angularjs,I'm using ng-repeat loop option,value="number:1" - angularjs

enter image description here
This situation causes the form submission parameter to become “number:1”。
Could you tell me why this problem happened?
javascript code as follows:
app.controller("Controller", function($scope,$http,$filter){
$http({
method:"POST",
url:"<%=request.getContextPath()%>/user.getUser",
params:{"name":name}
}).then(function successCallback(response) {
$scope.data = response.data;
}, function errorCallback(response) {
alert("00");
});
$http({
method:"POST",
url:"<%=request.getContextPath()%>/group.selectAll"
}).then(function successCallback(res) {
if(res != null && res != ""){
$scope.userGroups = res.data;
}
}, function errorCallback(response) {
alert("00");
});
}
jsp code as follows:
<select name="positionId" class="form-control"
ng-model="data.userGroup.GroupId" >
<option ng-repeat="p in userGroups" value="p.GroupId"
ng-value="{{p.GroupId}}">{{p.name}}
</option>
</select>

app.controller("Controller", function($scope,$http,$filter){
var userGroups={};
$http({
method:"POST",
url:"<%=request.getContextPath()%>/group.selectAll"
}).then(function successCallback(res) {
if(res != null && res != ""){
$scope.userGroups = res.data;
}
}, function errorCallback(response) {
alert("00");
});
$http({
method:"POST",
url:"<%=request.getContextPath()%>/user.getUser",
params:{"name":name}
}).then(function successCallback(response) {
//$scope.data = response.data;
$scope.userGroups.GroupId = "" + response.GroupId;
}, function errorCallback(response) {
alert("00");
});
}
After getting the values in the JS controller file, write dropdown list in the view page as below:
<select name="positionId" class="form-control"
ng-model="userGroups.GroupId" >
<option ng-repeat="p in userGroups" value={{p.GroupId}}>
{{p.name}}
</option>
</select>
If you want to set a particular value in a dropdown list to show while loading the dropdown then simply assign the value to the ng-model in the respective js controller file as below:
$scope.userGroups.GroupId = "" + response.GroupId; // based on your specific data
(Note: please check I have set ng-model as userGroups.GroupId and assigned userGroups={}; to initialize the userGroups to be used in the view page.)
Thanks.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.js"></script>
</head>
<body data-ng-app="role" data-ng-controller="fooController">
<select class="form-control"
ng-model="user.roles"
ng-options="role.id as role.name for role in roles"
required=""></select>
</body>
</html>
<script>
var app = angular.module('role', []);
app.controller('fooController', function($scope){
$scope.roles = [{id:0, name:"Select"},{id:1, name:"Administrator"}, {id:2, name: "Student"}];
$scope.user = {};
$scope.groupId = 1;
$scope.user.roles = $scope.roles[$scope.groupId].id ;
});
</script>
</html>

Related

Bind value to ng-init using ng-model

I have one select field and one 'input' field,for both fields am getting data from database.selected option will be checked defaultly based on db value.When I change dropdown option, balance field will be auto populated.Now my problem is,balance field value is auto populating when I change dropdown. But by default balance field value is not auto populating for selected option.Whats wrong here?Html:
<form ng-app="myApp" ng-controller="myCtrl" ng-repeat="data in leaveDetails">
<div>
<label>Leave Type</label>
<select type="text" ng-model="selectedName" ng-init="selectedName=data.LeavetypeId" ng-options="data.id as data.Name for data in leaveTypes" ng-change="leaveBalance(selectedName)"></select>
</div>
<div>
<label>Availabe Leaves</label>
<input type="text" ng-init="balanceCount=data.Balance" ng-model="balanceCount">
</div>
</form>
Script:
<script>
var app=angular
.module('myApp', [])
.controller('myCtrl', function ($scope, $http) {
$scope.init = function () {
$scope.loadEditLevDetails();
}
$scope.loadEditLevDetails = function (id) {
$scope.Id = { leaveRequestId: id };
var requestHeaders = {
'content-type': 'application/json'
}
var httpRequest = {
method: 'post',
url: "/user/details",
headers: requestHeaders,
data: $scope.Id
}
$http(httpRequest).then(function (response) {
$scope.leaveDetails = response.data;
})
}
$scope.leaveBalance = function (selectedvalue) {
$scope.leaveTypeId = { leaveTypeId: selectedvalue };
var requestHeaders = {
"content-type": 'application/json'
}
var httpRequest = {
method: 'POST',
url: '/user/balanceCount',
headers: requestHeaders,
data: $scope.leaveTypeId
}
$http(httpRequest).then(function (response) {
$scope.noOfValues = response.data;
$scope.balanceCount = $scope.noOfValues[0].balance_count;
})
}
})
</script>
Here is the sample code to implement what you are trying to do!! Hope it would help!!
<!doctype html>
<html lang="en" data-ng-app="test">
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
<script type="text/javascript">
angular.module('test',[])
.controller('Main',function($scope)
{
$scope.myModel = {};
$scope.options = [{opt:'1'},{opt:'2'},{opt:'3'}];
});
</script>
</head>
<body ng-controller="Main">
{{'Select'}}
<select ng-model="myModel.options" ng-options="data.opt for data in options" ng-init="myModel.options=options[0]"></select>
{{myModel.options}}
</body>
</html>

Angular function get data from $http requrest

I need to fetch data via $http request and i need to use it for Edit value for my form.
Example code
$http.get(base_url+"user/feach_one")
.then(function (response) {$scope.json = response.data;
$scope.name=$scope.json.name;
});
$scope.basic={
name:// I want to get $scope.json.name here
};
Bind your $scope to view, and create your form with your json params like this sample, read the comments
var app = angular.module("app", []);
app.controller("ctrl", function ($scope) {
//json
//uncomment in your local
//$http.get(base_url + "user/feach_one").then(function (response) {
// var json = response;
// $scope.form = json;
//});
//we didn't have api here: { name: "Test", age: 20 }
//comment in your local
var json = { name: "Test", age: 20 }
$scope.form = json;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<form>
<label>name</label>
<input type="text" ng-model="form.name"/>
<label>age</label>
<input type="text" ng-model="form.age"/>
</form>
</div>
$scope.basic= {};
$scope.advanced= {};
$http.get(base_url+"user/feach_one")
.then(function (response) {
$scope.basic.name=$scope.json.name;
$scope.advanced=$scope.json.avanced;
});

TokenMismatchException in VerifyCsrfToken in Laravel 5.1 + angular

I have Laravel 5.1 + angular form sending JSON request when user want to send mail from website feedback form.
I did my form according to documentation here https://laravel.com/docs/master/csrf and anyway I get error message TokenMismatchException in VerifyCsrfToken.php line 53:
I found a lot of topics on stackoverflow, but no real solution.
Is there?
in header of my layout I have
<meta name="csrf-token" content="{!! csrf_token() !!}">
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
then in my form I have this
<form name="callback" ng-controller="callbackController" role="form" class="" enctype="multipart/form-data">
{!! csrf_field() !!}
...
...
<button type="submit" class="btn btn-primary pull-right" ng-click="submit(callback.$valid)" ng-bind="submittext" ng-class="{ 'btn-danger': callback.name.$touched && callback.name.$invalid || callback.tel.$touched && callback.tel.$invalid, 'btn-success': callback.name.$touched && callback.name.$valid && callback.tel.$touched && callback.tel.$valid, }">Send</button>
</form>
here is the code of my angular
angular.module('myapp', ['ngMessages', 'angularFileUpload'])
.controller('callbackController', function($scope, $http, $timeout) {
$scope.formData = {};
$scope.url = '/';
$scope.submittext = 'Отправить';
$scope.submit = function(isValid) {
if (isValid) {
$scope.submittext = 'Отправляем...';
$http.post($scope.url,
{
"formname": "callback",
"name": $scope.name,
"tel": $scope.tel,
"time": $scope.time,
"email": $scope.email,
"msg": $scope.msg
}).
success(function(data, status) {
console.log(data);
$scope.status = status;
$scope.data = data;
$scope.result = data;
});
$timeout(function() {
$('#callback').modal('hide');
$scope.submittext = 'Отправить';
$scope.name = null;
$scope.tel = null;
$scope.time = null;
$scope.email = null;
$scope.msg = null;
$scope.callback.$setPristine();
$scope.callback.$setUntouched();
}, 1000);
} else {
$('.errors').modal('show');
}
}
})
The problem with your code is that the second line in the form
{!! csrf_field() !!}
generates some code like:
<input type="hidden" name="_token" value="ZwiQQ3BJFbWMr4goixtcklwGvpxIeN8vkWNinHIL">
which is not what you need.
Just like the link you have posted, you need to put the following line in the head area:
<meta name="csrf-token" content="{{ csrf_token() }}">
because using ajax, you are adding a header which picks its value by looking for a meta tag which has the name csrf-token

$http.post() does not work - (AngularJS)

I am trying to create a form with a dropdown input field and a submit button in AngularJS. Everything works fine except the output is empty xD. I am using <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>. And if it's any help on server side I am using PHP Version 5.5.36-1+donate.sury.org~trusty+1.
Here's the Angular code:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.myTxt = "You have not clicked submit, yet!";
$scope.show_result = false;
$scope.myFunc = function() {
$scope.myTxt = "You clicked submit!";
$scope.show_result = true;
}
$scope.categories = [
{"value": 0, "categoryname": "standard"},
{"value": 1, "categoryname": "premium"},
{"value": 2, "categoryname": "gold"}
];
$scope.submitData = function() {
$scope.category = {};
console.log($scope.category);
var jsonString = JSON.stringify($scope.category);
$http.post('ServerController.php', jsonString, {'Content-Type': 'application/x-www-form-urlencoded'})
.success(function(data, status) {
$scope.status = status;
$scope.data = data;
});
}
});
Here is the ServerController.php :
$jsonString = file_get_contents('php://input');
$form_data = json_decode($jsonString, true);
if ($form_data != null) {
echo 'Success!!!';
var_dump($form_data);
} else {
echo 'Sorry!!!';
var_dump($form_data);
}
Here is the HTML:
<body ng-app="plunker">
<form ng-submit="myFunc()" ng-controller="MainCtrl">
<label><b>Category:</b></label>
<select ng-model="category" ng-options="x.categoryname for x in categories track by x.value">
<option value="">Choose a Category</option>
</select>
<p><b>Model:</b> {{category}}</p>
<input ng-click="submitData()" type="submit" value="Submit"></input>
<i>{{myTxt}}</i>
<p ng-show="show_result"><b>Submitted result:</b> {{data}}</p>
</form>
</body>
Here is how the form looks on page load:
This is after you select category in the dropdown:
And finally after clicking submit:
Note: The server controller is sending the output in Submitted result ie. Sorry!!!<pre class='xdebug-var-dump' dir='ltr'> <b>array</b> <i>(size=0)</i> <i><font color='#888a85'>empty</font></i> </pre>
Any ideas?

Can't send a POST request with $http in Angular - ReferenceError: $http is not defined

So I keep getting this ReferenceError: $http is not defined, even though I have included $http in the controller, which seems to be the most common cause of this error message. I've tried also passing $http into the function itself, but that doesn't solve it.
I feel like I am missing something SUPER obvious, so any help would be much appreciated, thank you!
I've included the entire script, just for clarity's sake. You can see the post request towards the end of the script, inside the finaliseDay function.
Thanks!
Here is the error:
ReferenceError: $http is not defined
at l.$scope.finaliseDay (http://localhost:8888/goalzy.js:69:12)
at ib.functionCall (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:198:303)
at Dc.(anonymous function).compile.d.on.f (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:214:485)
at l.$get.l.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:125:305)
at l.$get.l.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:126:6)
at HTMLAnchorElement.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:215:36)
at HTMLAnchorElement.c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:32:389)angular.js:11607 (anonymous function)angular.js:8557 $getangular.js:14502 $get.l.$applyangular.js:21440 (anonymous function)angular.js:3014 c
Here is the HTML first
<!doctype html>
<html ng-app="goalzy">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
<script src="goalzy.js"></script>
</head>
<body>
<div class="container">
<div class="well">
<h2>Goalzy</h2>
Dev TODO
<ul>
<li>Hook up the API to persist data</li>
</ul>
<div ng-controller="TodoController">
<span>{{remaining()}} of {{todos.length}} remaining today</span>
<span>You're at {{percentComplete()}}% completion</span>
[ finalise day ]
<ul class="unstyled">
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</li>
</ul>
<form ng-submit="addTodo()">
<input type="text" ng-model="todoText" size="30"
placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
<hr>
<div class="historial" ng-repeat="h in historicalDailyPercentages">
<ul>
<li>Date: {{h.date}}</li>
<li>Percentage of Daily Tasks Completed: {{h.percent}}%</li>
<li><div>Tweet it!</div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
And here is the JS:
//Goalzy.js
angular.module('goalzy', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
});
.controller('TodoController', ['$scope','$http', function($scope, $http) {
$scope.todos = [];
$scope.historicalDailyPercentages = [];
$scope.addTodo = function() {
if ($scope.todoText != "") {
if ($scope.todos.length < 3) {
$scope.todos.push({text:$scope.todoText, done:false});
$scope.todoText = '';
//Save to DB
}
else {
alert("You can only have 3 todos per day!");
$scope.todoText = '';
}
} else {
alert("you must write something");
}
};
$scope.remaining = function() {
var count = 0;
angular.forEach($scope.todos, function(todo) {
count += todo.done ? 0 : 1;
});
return count;
};
$scope.percentComplete = function() {
var countCompleted = 0;
angular.forEach($scope.todos, function(todo) {
countCompleted += todo.done ? 1 : 0; //Simply calculates how many tasks have been completed
console.log(countCompleted);
});
var totalCount = $scope.todos.length;
var percentComplete = countCompleted / totalCount * 100;
return percentComplete;
}
$scope.finaliseDay = function(percentComplete) {
alert("You're finalising this day with a percentage of: " + percentComplete);
var today = new Date();
var alreadyPresent = $scope.historicalDailyPercentages.some(function (item) {
return item.date.getFullYear() === today.getFullYear() &&
item.date.getMonth() === today.getMonth() &&
item.date.getDate() === today.getDate();
});
//Confirm that nothing has alreayd been posted for today
if (!alreadyPresent) {
$scope.historicalDailyPercentages.push({
percent: percentComplete,
date: today
});
// Simple POST request example (passing data) :
$http.post('/api/postDailyPercentage.php', {msg:'hello word!'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("data" + data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("data" + data);
});
}
else {
alert("You're all set for today - see you tomorrow!");
}
console.log($scope.historicalDailyPercentages);
}
}]);
Provider won't be available inside controller with suffix 'Provider', you can do access them by provider name only here it would be $http only, also remove ;
after config initialization
$httpProvider setting should be done inside the angular config phase
CODE
angular.module('goalzy', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
}]);
.controller('TodoController', ['$scope', '$http', function($scope, $http) {
//controller code here
}]);
Note: For sure you should remove $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8'; line from controller
Working Plunkr
You don't have to use "$httpProvider" in controller, use $http instead.
e.g.
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
As best practice, do not configure provider ($http) in controller. Do it in config section. as below
var app = angular.module('goalzy', []);
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
});
app.controller('TodoController', ['$scope','$http', function($scope, $http) {
$scope.title="scope title";
//$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}]);
see working plunk at http://run.plnkr.co/plunks/4mY4izqc48P8wVQFumZ8/ with your html.

Resources