ng-options is not displayed all the time in AngularJS - json

I have a small problem when I load my page. Sometimes, my ng-options has blank values. I don't understand why. I can load the page 10 times without problem, but I can load the page with blank values.
However, JSON returned is not blank. Always the same result :
SERVICE :
myApp.factory('GenericService', function ($http, $q) {
var data;
function getDataIfNeeded(the_action) {
the_action = the_action || 'default';
if (data !== undefined) {
return $q.when(data);
}
return $http({
url: "php/functions.php",
method: "GET",
params: {
action: the_action
}
}).then(function(response) {
data = response.data;
return data;
});
}
return {
getData: getDataIfNeeded
};
});
CONTROLLER :
GenericService.getData("get_leaders").then(function (data) {
$scope.leaders = data;
});
...
GenericService.getData("get_experts_ux").then(function (data) {
$scope.experts_ux = data;
});
JSON :
[
{"lead_technique_id":1,"lead_technique_name":"Delphine ____"},
{"lead_technique_id":2,"lead_technique_name":"Thierry ____"}
]
HTML :
<select ng-model="newProject.lead_technique_id" ng-options="leader.lead_technique_id as leader.lead_technique_name for leader in leaders" required></select>

Related

Laravel Return Value from Controller via JS Get Method

I am trying to create a Request via Axios JS to the API Route and trying to send the data from the database over the controller back to the view of the page. When I am just put an string as return value it is working.
I am always getting following a 500 Error.
JS File
function getSelectedItem() {
var e = document.getElementById("Objekt");
if (e.value > 0) {
axios({
method: 'get',
url: '/api/zimmer/' + e.value,
responseType: 'stream'
})
.then(function(response) {
zimmer_select.disabled = false;
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
} else {
zimmer_select.disabled = true;
}
console.log(e.value);
}
API Route:
Route::controller(MieterController::class)->group(function () {
Route::get('/zimmer/{id}', 'relocate_update')->name('api.get.zimmer');
});
Controller:
public function relocate_update($id) {
$zimmer_zu_objekt = Zimmer::findOrFail()->where('objekt_id', $id);
return response()->json(['alle_zimmer' => $zimmer_zu_objekt], 200);
}
I got it.
I changed it to VanillaJS and the main problem was my Eloquent Query in the Controller. Corret is
return Zimmer::where('objekt_id','=', $id)->get();
and used the fetch-method is JS:
fetch('/api/zimmer/' + e.value)
.then(function(response) {
zimmer_select.disabled = false;
console.log(response.json());
})
.catch(function(error) {
console.log(error);
});

Redirect to diffrent action when reciving json results in my script

i'm getting a list view json results and I would like to redirect to a different view and display the results according to my json
( I hope i'm clear) this what i'm did
<script type="text/javascript">
$(document).ready(function () {
$("#term").autocomplete({
source: function (request, response) {
$.ajax({
url: "Home/GetSubjectsName",
data: "{'term': '" + request.term + "' }",
dataType: 'json',
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.value,
value: item.value,
id: item.id,
}
var url = '#Url.Action("bla", "blaaaa")';
}))
}
});
},
minLength: 2,
});
});
my jsonlook like this :
public JsonResult GetSubjectsName(string term)
{
var results = db.subjects.Where(s => term == null ||
s.SubjectName.ToLower().Contains(term.ToLower())).Select(x => new
{ id = x.SubjectId, value = x.SubjectName }).Distinct().ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
and the action I would like to display the results is this (instead of partial view)
public ActionResult bla(string term)
{
IEnumerable serach = from sub in db.subjects.Where(t => t.SubjectName.Contains(term)).Distinct()
select new SearchResultsViewModel
{
Created = sub.Created,
Gender = sub.Gender,
OccupationDecription = sub.OccupationDecription,
Image = sub.Image,
SubjectName = sub.SubjectName
};
ViewBag.term = term;
return RedirectToAction("bla", "home", serach.ToList());
}
my View :
#model IEnumerable<MyProJect.ViewModels.SearchResultsViewModel>
foreach ....
what I need is to go to a different action and display the data
Here's some code that might help. Your post is still a bit unclear, so I'm filling in the missing pieces according to what you have described. I've made no attempt at designing the form layout.
Home/Index.cshtml:
#using( Html.BeginForm("bla") ) {
#Html.LabelFor(model => model.term)
#Html.EditorFor(model => model.term)
<button type="submit">Submit</button>
}
<script type="text/javascript">
jQuery(function ($) {
$("#term").autocomplete({ source: '#Url.Action("GetSubjectsName")', autoFocus: true, minLength: 2 });
});
</script>
Your autocomplete should be changed to:
public JsonResult GetSubjectsName(string term)
{
return Json(db.subjects
.Where(s => term == null ||
s.SubjectName.ToLower()
.Contains(term.ToLower()))
.OrderBy(x => x.SubjectName)
.Select(x => x.SubjectName)
.Distinct(), JsonRequestBehavior.AllowGet);
}
As far as I can tell, everything else should work as intended.

How to map URL to node.js route

I am using ui-router with Angular and Node.js as my UI server for API calls to another server. Right now, my browser URL (dynamic based on dropdown selections) does not map to the server.
For example, the browser URL is "/home?color=Red&&size=Large" when I send the user inputs to Node. When I copy and paste that URL in another browser window, I want the color and size dropdowns to already be selected as Red and Large, and results from API call based on the selections displayed. How can I accomplish this?
My AngularJS controller code:
$scope.getResults = function() {
$location.search('color', $scope.myColor);
$location.search('size', $scope.mySize);
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};
AngularJS service for the above function:
app.factory('server', ['$http', function($http){
return {
getResults : function(color, size) {
var req = {};
req.color = color;
req.size = size;
return $http({
method: 'GET',
url: 'results',
params : req
});
}
}
}]);
ui-router in Angular:
$stateProvider.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
reloadOnSearch: false
})
In Node.js, I have my route like this:
app.get("/results", function (req, res) {
var api = 'some api call/' + req.query.color + '/' + req.query.size;
request(api, function (error, response, api) {
if (!error && response.statusCode == 200) {
res.json({
Response: api
});
}
});
});
In your code you wrote query parameters but you need to read them, try this:
$scope.getResults = function() {
$scope.myColor = $location.search().color;
$scope.mySize = $location.search().size;
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};

retrieve json data using GET in angularjs

I've got some data stored in a nosql database that I'm able to see in when accessing localhost:3000/countries.
I'm trying to use this factory in order to get the data which is in json.
.factory('countries', ['$http', '$q',
function($http, $q) {
var countries = {
get: function() {
return $q(function(resolve, reject) {
$http({
method: 'GET',
url: '/countries'
}).then(function(response) {
resolve(response.data);
}, function(error) {
reject(error);
});
});
};
return countries;
}
]);
And then I'm attempting to use this controller to send that data to the appropriate url to be displayed but it isn't working as I expected it to.
.controller('CountriesCtrl', function($scope, countries) {
console.log(countries);
countries.get(function(countries) {
$scope.countries = countries;
});
})
Any thoughts or suggestions? Thanks!
This is what I use currently in my project that uses Mongodb
cmsApp.factory("tasks", ["$resource", function($resource) {
return $resource("/tasks/", {}, {
save: {
method: 'POST',
isArray: true
},
'delete': {
method: 'DELETE',
isArray: true
}
});
}]);
Then in the Controller(make sure to inject it to controller!):
$scope.tasks = tasks.query();
.query() selects all of the data while .get() gets on by Id
You should inject your factory into your controller, something like this:
.controller('CountriesCtrl', function($scope, devices) {
console.log(countries);
countries.get(function(data) {
$scope.data = data;
});
})
You should inject service 'devices' instead of it's internal variable 'countries'.
.controller('CountriesCtrl', function($scope, devices) {
console.log(devices);
devices.get().then(function(countries) {
$scope.countries = countries;
});
});

How to load more than one json file in angular

I am wondering how to load multiple .json files in to template.
In my example I have submissions from users and I do not want to store everything in one json file if possible.
How to grab some data from multiple json files?
here is my plunk example
I want to load users.json as well
var app = angular.module('myApp', []);
app.directive('contentItem', function ($compile,$parse) {
templates = {
image: 'image.html',
event: 'event.html',
article: 'article.html',
ad: 'ad.html',
discount: 'discount.html',
video: 'video.html'
}
var linker = function(scope, element, attrs) {
scope.setUrl = function(){
return templates[scope.content.content_type];
}
}
return {
restrict: "E",
replace: true,
link: linker,
scope: {
content: '='
},
templateUrl: 'main.html'
};
});
function ContentCtrl($scope, $http) {
"use strict";
$scope.url = 'content.json';
$scope.content = [];
$scope.fetchContent = function() {
$http.get($scope.url).then(function(result){
$scope.content = result.data;
});
}
$scope.fetchContent();
}
Help appreciated
You can request for JSON either from the controller like:
app.controller('myController', function($scope, $http){
$scope.users = [];
$scope.getUsers = function() {
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).
success(function(data, status) {
$scope.users = data;
}).
error(function(data, status) {
console.log(data || "Request failed");
});
};
and the other approach (better one) would be to make use of angular factory to fetch the JSON file.
myApp.factory('getUsersFactory',['$http',function($http){
return {
getUsers: function(callback){
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).success(callback);
}
}
}]);
where now you can include this factory as a dependency and get the user data and assign that in the callback function.