How can i check if the id that i get from the url is equal to any of the ids in the json api here is my code
.controller('PlayAod', ['$scope', '$http', '$state', '$stateParams', '$location', function ($scope, $http, $state, $stateParams) {
$scope.title = 'Sample Company';
$scope.apiusername = 'hoy';
$scope.apipassword = '076fdf74936ebae00e7949a80f61f985';
$scope.aodid = $stateParams.ahls;
$scope.stream = "";
$http.get('http://tvstartup.biz/mng-channel/vpanel/api/audios.php?user=' + $scope.apiusername + '&pass=' + $scope.apipassword).success(function (data) {
$scope.aodhls = data.audios;
if (data.audios.id == $scope.aodid) {
$scope.stream = date.audios.hls_stream;
}
});
$scope.play = function() {
window.cndStream.play($scope.stream);
}
$scope.pause = function() {
window.cndStream.pause();
}
}])
please help if you have any questions post in comments
As I have experience with your problem from another question, I will add context for other users that your $http request here returns an array of objects, and each of the objects has a property named 'id'.
Assuming that you are trying to track down the particular object within the array of which object.id == $scope.aodid, you can search over the array until the comparative proves true. One such example would be:
// Inside of $http.get success function
var audioList = data.audios;
for(var audio of audioList) {
if(audio.id == $scope.aodid) {
// Oh, joy this is the one I want!
// Perform some magic...
// Or maybe in your case...
$scope.stream = audio.hls_stream;
// Dont forget to stop searching...
break;
}
}
A potentially better solution would be to provide the ID in the query such that you only get back what you want and don't have to iterate a list, however I am infering a bit as to what you are ultimately trying to do.
Related
I have a problem accessing to a scope variable defined in a nested $http.get. This is my controller code (it's related to a partial $routeProvider)
//Content controller
app.controller('Content', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) {
$http.get('wp-json/wp/v2/posts?slug=' + $routeParams.slug).success(function(res) {
$scope.post = res[0];
document.querySelector('title').innerHTML = res[0].title.rendered + ' | Going Solo ';
console.log(res);
$http.get('wp-json/wp/v2/posts?filter[artists]=' + $scope.post.pure_taxonomies.artists[0].slug + '&exclude=' + $scope.post.id).success(function(res) {
if (res.length > 1) {
$scope.related = res;
}
else {
$scope.related = res[0];
}
console.log(res);
});
}).error(function(res, status) {
if (status === 404) {
$scope.is404 = true;
document.querySelector('title').innerHTML = 'Page not found | Going Solo';
$scope.errorMessage = 'Error: ' + res[0].message;
}
});
}]);
Basically I want to retrieve all the songs related to the one that is showed in my content controller (the first $http.get). To link all the songs I use a custom taxonomy called “artists”. Of course I need this to be asynchronous so I do a new $http.get inside the first one. In this request I filter for the taxonomy slug of the current post ($scope.post.pure_taxonomies.artists[0].slug) plus I add a filter to exclude the post itself by adding its ID. This is working correctly by looking at the console log. It returns an array(1) for the first request and an array(2) for the second requests (with the correct data).
The problem is by the time I try to access in my partials to the second $http.get.
If I try this ng-repeat:
<div ng-repeat="songrel in related">
<div ng-bind-html="songrel.title.extended"></div>
</div>
Nothing is showed. It simple doesn't enter in this cycle, so I guess he doesn't recognize data.related. What am I missing?
It can't find data.related because there's no $scope.data variable declared. Try just related, i.e.
<div ng-repeat="songrel in related">
<div ng-bind-html="songrel.title.extended"></div>
</div>
As the title says, I have a problem with reference switching.
My html:
div ng-repeat="data in parseurl">
{{data.url}}
</div>
In my JS code, I'm trying to do two things. The first step is to grab the data off a server and put it into an array (called allsongs). Afterwards, I parse the data and put it into another array (parseurl).
var app = angular.module("write", []);
app.controller("Ctrl", ['$scope', '$http', function($scope, $http){
$scope.allsongs = [];
$scope.parseurl = [];
$scope.getstuff = function(){
$http.get("my link here").then(function(response){
$scope.allsongs = response.data;
}); //step one -> this works!
$scope.parser(); //step two
};
$scope.parser = function()
{
for(i=0;i<$scope.allsongs.length;i++) {
for(var key in $scope.allsongs[i]) {
var value = $scope.allsongs[i][key];
var object = {Url : value.Url}; //this does contain the correct info I want
$scope.parseurl.push(object);
}
$scope.getstuff();
}]);
So what is happening is that, if I ng-repeat on allsongs, then I do get a bunch of un-parsed urls. But if I ng-repeat on parseurl, then I get nothing. Obviously the reference isn't changing, but how can I do it?
$scope.parser() needs to be called after the data was recived. Put it into your promise callback function like in the following example. Please note that $http is an asynchronous function. In that way $scope.parser() was executed before your request has been finished.
$scope.getstuff = function(){
$http.get("my link here").then(function(response){
$scope.allsongs = response.data;
$scope.parser();
});
};
I would like to use AngularJS smart table for my site. I have gone through the documentation(smart table). Having hard time to understand how does the app.factory works here. I want to know how to implement createRandomItem function for the data I have in the database(mongodb).
app.factory('Resource', ['$q', '$filter', '$timeout', function ($q, $filter, $timeout) {
//this would be the service to call your server, a standard bridge between your model an $http
// the database (normally on your server)
var randomsItems = [];
function createRandomItem(id) {
var heroes = ['Batman', 'Superman', 'Robin', 'Thor', 'Hulk', 'Niki Larson', 'Stark', 'Bob Leponge'];
return {
id: id,
name: heroes[Math.floor(Math.random() * 7)],
age: Math.floor(Math.random() * 1000),
saved: Math.floor(Math.random() * 10000)
};
}
for (var i = 0; i < 1000; i++) {
randomsItems.push(createRandomItem(i));
}
//fake call to the server, normally this service would serialize table state to send it to the server (with query parameters for example) and parse the response
//in our case, it actually performs the logic which would happened in the server
function getPage(start, number, params) {
var deferred = $q.defer();
var filtered = params.search.predicateObject ? $filter('filter')(randomsItems, params.search.predicateObject) : randomsItems;
if (params.sort.predicate) {
filtered = $filter('orderBy')(filtered, params.sort.predicate, params.sort.reverse);
}
var result = filtered.slice(start, start + number);
$timeout(function () {
//note, the server passes the information about the data set size
deferred.resolve({
data: result,
numberOfPages: Math.ceil(filtered.length / number)
});
}, 1500);
return deferred.promise;
}
return {
getPage: getPage
};
}]);
Ok... My Time to Shine.. :D.... Just kidding.. you answer is bellow..
Well this a fairly straight forward example, if you are familiar with angular factory.
when you use a factory service it executes the code inside the factory's definition and return whatever you would just like calling a function.
So what the above code is doing is when you use this factory service simply generates a list of random items(Avengers) into the array randomItems that step is fairly simple. if you look at the createRandomItem(id) and the for loop after it.
the trick however is in getPage() and what the Resource factory is returning. So lets go on a journey.
in the code where Resource factory is used when you call Resourse.getPage() it'll return a promise object on which you can call other JS functions. and inside getPage() as you can see it has set a timeout to call resolve with an object that has variables data and numberOfPages in it, on the deffered object which triggers doneCallback on the promise of that deffered object.
so when you service like
Resourse.getPage(1,2,3) // please see the use of these arguments inside the getPage function
.done(function(result){
result.data; //the fake server data from the factory
result.numberOfPages; //this is computed in factory as well
});
When 1500ms pass the function/callback passed to done gets trigerred.
Summary and Answer
Note: Please read above first it took me hell of a time to write that.
Now to address your problem. what you can do is modify this
app.factory('Resource', ['$q', '$filter', '$timeout', function ($q, $filter, $timeout)
to
app.factory('Resource', ['$http', '$q', '$filter', '$timeout', function ($http, $q, $filter, $timeout)
an use $http to retrieve data from the server or mongodb and fill in an array with your data from server.
$http.get(server_url).success(function(response){
//....do something with the response from the server like filtering etc..
//finally..
deferred.resolve({
data: response
});
});
an finally when using service
Resourse.getPage(1,2,3) //what ever you want to pass its not necessory to pass the same as above
.done(function(response){
//do what ever you want to do with response from your factory.. PHEW...
});
P.S.0. its the longest answer I've provided to date.. PHEW :P
P.S.1. Please feel free to ask any question in the comments
I am trying to work with AngularJS and a Web API written in VB.NET (Doing this for my internship).
I have my angularApp defined, same for my controller and factory.
I'm also working with the routing from Angular and this works perfectly.
The issue I'm dealing with is that my factory isn't activated or isn't working.
Please take a look at the code below:
My AngularApp.js
var angularApp = angular.module('AngularApp', ['ngRoute']);
angularApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/ExpenseOverview', {
controller: 'ExpenseController',
templateUrl: 'Views/ExpenseOverview.aspx'
})
.when('/AddExpense',
{
controller: 'ExpenseController',
templateUrl: 'Views/AddExpense.aspx'
})
.otherwise({ redirectTo: '/ExpenseOverview' });
}]);
My ExpenseController:
angular.module("AngularApp").controller("ExpenseController", ["$scope", "ExpenseFactory", function ($scope, ExpenseFactory) {
//variabelen
$scope.expenses = [];
$scope.id = 0;
$scope.date = "";
$scope.type = "";
$scope.title = "";
$scope.project = "";
$scope.status = "";
$scope.img = "";
var shown = false;
var dataURL = "";
ExpenseFactory.getList($scope);
}]);
So far my controller isn't doing much more other than retrieving a list of data from the database through the web API.
My ExpenseFactory.js
angular.module("AngularApp").factory("ExpenseFactory", ["$http", function ($http) {
alert("test factory");
var factory = {};
//lijst van expenses ophalen
factory.getList = function ($scope) {
$http.post("/api/Expense/List")
.success(function(data) {
if (data === undefined || data == "") {
data = [];
}
$scope.expenses = data;
$scope.id = $scope.expenses[$scope.expenses.length - 1].Id + 1;
})
.error(function() {
alert("Er is een fout opgetreden");
});
};
factory.saveList = function(expenseList) {
$http.post("/api/Expense/SaveList", { 'expenses': expenseList })
.success(function() {
alert("Expenses have been saved succesfully!");
})
.error(function() {
alert("Something went wrong while saving the expenses");
});
};
return factory;
}]);
As you can see, I have put an alert as the first line of code in the factory. This alert isn't even popping up, which means the factory isn't activating/working.
What is failing in this code?
EDIT
I updated my code to the current version with all the comments about things that might be interfering with the code. I can confirm that none of this was working, so the error is occuring somewhere else.
Another note: I'm working with Visual Studio 2012, if this might have something to do with it, please do elaborate how I can fix this shenannigans.
You missed to return $http promise from factory methods
factory.getList = function ($scope) {
return $http.post("/api/Expense/List")
.success(function(data) {
if (data === undefined || data == "") {
data = [];
}
$scope.expenses = data;
$scope.id = $scope.expenses[$scope.expenses.length - 1].Id + 1;
})
.error(function() {
alert("Er is een fout opgetreden");
});
};
factory.saveList = function(expenseList) {
return $http.post("/api/Expense/SaveList", { 'expenses': expenseList })
.success(function() {
alert("Expenses have been saved succesfully!");
})
.error(function() {
alert("Something went wrong while saving the expenses");
});
};
Rather than passing whole scope, you should create one model object like $scope.model = {} and that will hold the all value of ng-model (scope variables) don't pass whole scope to factory, Pass only relevant data to service method.
As the app, controller and factory are in different files, it's better to avoid referencing the module using angularApp.
Instead use the following syntax:
angular.module('AngularApp').factory("ExpenseFactory", ["$http", function ($http) {
Here,
angular.module('AngularApp')
Means you're getting the module.
If you're going to use var angularApp, you're actually polluting the global namespace with your variable name.
Also if by chance in some other library code, someone reassigns it to something else then your entire application will break.
for example:
in another file, `angularApp = alert;`
And one more thing,
In your controller:
angularApp.controller("ExpenseController", ["$scope", "ExpenseFactory", function ($scope, expenseFactory) {
You have a typo in expenseFactory as it must be ExpenseFactory
angularApp.controller("ExpenseController", ["$scope", "ExpenseFactory", function ($scope, ExpenseFactory) {
Thank you #mohamedrias for helping me find to solution.
It was indeed because of the URL Path that was invalid.
Because of the view that couldn't be loaded, the factory was crashing alongside it.
I don't know how this happened, but it's fixed now!
All the code was correct, except for a reference to an invalid URL path for my views.
Thanks for all the help and comments, I'll keep everything in mind for the upcoming parts of my project.
StackOverflow is awesome!
Everything works fine but I have problem getting source from service.
I have SERVICE code below.
app.factory('myService',
function($rootScope, ResourceData) {
var result = {};
var data = ResourceData.query();
result.getData = function() {
// problem here
}
return result;
});
And CONTROLLER contain code.
app.controller('myController', ['$scope', 'myService',
function myController($scope, myService) {
$scope.data = myService.getData();
});
My problem is if I have function in my SERVICE like this
result.getData = function() {
return data;
}
Everything works fine but I need to filter that data before I get it
If I change body like this I get an empty array the problem seems like it is from AngularJS.
If I create static array it works.
result.getData = function() {
var arr = [];
angular.forEach(data, function(item, key) {
// simple filter
if(item.ID > 10) {
return;
}
else {
arr.push(item);
}
});
return arr;
}
The result of "ResourceData.query()" is asynchronous:
When the data is returned from the server then the object is an instance of the resource class... It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.
When the page first loads, I'm guessing that the controller runs before the data is returned from the server, so the first time getData() is called, data is probably not yet populated with any data, so you get an empty array.
One solution to your problem would be to filter the data in the view/HTML with an Angular filter, rather than in the service.
<div ng-repeat="item in data | filter:myFilter">
{{item.ID}}: {{item...}}
</div>
Then in your controller:
$scope.myFilter = function(item) {
return item.ID <= 10;
}