i want to my put http json files in slides.push(). so here i used ui.bootstrap.carousel , and i want to set image in my html .
So how can i do it . can someone help me?
.controller('dashboardCtrl', ['$scope', '$http', '$location','$timeout', function ($scope, $http, $location, $timeout) {
$http.get('json/login.json').success(function (data) {
$scope.info = data.profile[0];
$scope.pic = data.offers[0];
console.log($scope.pic);
})
$scope.myInterval = 500;
$scope.noWrapSlides = false;
$scope.active = 0;
var slides = $scope.slides = [];
var currIndex = 0;
$scope.addSlide = function() {
// var newWidth = 600 + slides.length + 1;
slides.push({
image: '../image/slide1.png',
id: currIndex++
},
{
image: '../image/slide2.png',
id: currIndex++
},
{
image: '../image/slide3.png',
id: currIndex++
}
);
};
Just put your slides.push to $http.get function, like here:
$scope.get = function() {
$http({
method: 'GET',
url: 'json.json'
})
.then(function successCallback(data){
$scope.img = data.data;
slides.push({
image: $scope.img[0].url,
id: currIndex++
});
}, function errorCallback(response){
console.log(response);
console.log('error');
});
}
Also you can add all url from json.json through some kind of loop .In my code I am pusshing first url from json.
Here is plunker : http://plnkr.co/edit/27RvnjGCT5i0MCNooZeB?p=preview
Related
I was trying to parse JSON array in AngularJS. But it's not working. If the array is written directly it's working. Help me to solve the issue. The code I have been using is below.
(function () {
var app = angular.module('store', ['ngCookies']);
app.controller('StoreController', ['$scope', '$cookies', function ($scope, $cookies) {
$scope.products = JSON.parse(SuccessItems);
$scope.cart = [];
$scope.total = 0;
var expireDate = new Date();
expireDate.setDate(expireDate.getDate() + 1);
$cookies.putObject('cart', $scope.cart, { 'expires': expireDate });
$scope.cart = $cookies.getObject('cart');
$scope.total += parseFloat(product.price);
$cookies.put('total', $scope.total, { 'expires': expireDate });
};
}]);
var SuccessItems = '';
$.ajax({
type: "POST",
url: "code.aspx/RetrieveItems",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (jsondata) {
SuccessItems = jsondata.d.replace(/"(\w+)"\s*:/g, '$1:').replace(/"(\d[.]\d+)"/g, "$1");
},
error: function (xhr, ajaxOptions, thrownError) {
errMsg = JSON.parse(xhr.responseText).Message;
alert(baseErrorMsg + 'Error Code : ' + errMsg);
}
})
})();
I'm hoping this is an easy question to answer...
I'm trying to create a table that loads my json, then be able to click a row and load more details that pertain to the json object. When you click a row it should load additional details at the top of the page. The row clicking part is working fine. What I'm having trouble with is loading the initial object by default.
Below is an example of what I'm referring to:
var myItemsApp = angular.module('myItemsApp', [ ]);
myItemsApp.factory('itemsFactory', ['$http', function($http){
var itemsFactory = {
itemDetails: function () {
return $http({
url: "fake-phi.json",
method: "GET",
}).then(function (response) {
return response.data;
});
}
};
return itemsFactory;
}]);
myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory',
function($scope, itemsFactory){
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
console.log(data);
});
$scope.select = function (item) {
$scope.selected = item;
}
}]);
http://embed.plnkr.co/6LfAsaamCPPbe7JNdww1/
I tried adding this after $scope.select, but got an error:
$scope.selected = item[0];
How do I get the first object in my json to load by default?
thanks in advance
Inside your promise resolve function assign the first item of the array, as a selected value:
promise.then(function (data) {
$scope.itemDetails = data;
$scope.selected = data[0];
console.log(data);
});
var myItemsApp = angular.module('myItemsApp', [ ]);
myItemsApp.factory('itemsFactory', ['$http', function($http){
var itemsFactory = {
itemDetails: function () {
return $http({
url: "fake-phi.json",
method: "GET",
}).then(function (response) {
return response.data;
});
}
};
return itemsFactory;
}]);
myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory',
function($scope, itemsFactory){
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
$scope.selected = data[0];
console.log($scope.itemDetails);
console.log($scope.selected);
});
}]);
Can some one please explain how can I call an action using Angular in MVC project?
I managed to call action using Ajax like this:
var app = angular.module('toprightSec', ['ng']);
app.controller('NationalityCtrl', ['$scope', function ($scope, $http) {
$scope.items = [];
var items = populateListFromLocalStorage("offices", "Login/GetOffices", 24);
var officelist = "";
for (var i = 0; i < items.length; i++)
{
$scope.items[i] = { "name": read_prop(items[i], 'office_desc'), "guid": read_prop(items[i], 'office_guid') };
}
$scope.reloadPage = function () { window.location.reload(); }
$scope.getResult = function ($index, item) {
$.ajax({
type: 'GET',
async: true,
url: 'Login/ChangeOffice',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
officeID: $scope.items[$index].guid,
officeName: $scope.items[$index].name,
},
success: function (msg) {
}
});
};
}]);
I tried changing it to Angular like this:
var AngularModule = angular.module('toprightSec', ['ng']);
AngularModule.service('ApiCall', ['http', function ($http) {
var result;
this.PostApiCall = function (controllerName, methodName, obj) {
debugger;
result = $http.post('api/' + controllerName + '/' + methodName,obj).success(function (data, success) {
result = (data);
}).error(function () {
("Something went wrong");
});
return result;
};
}]);
AngularModule.controller('NationalityCtrl', ['$scope', function ($scope, $http, ApiCall) {
$scope.items = [];
var items = populateListFromLocalStorage("offices", "Login/GetOffices", 24);
var officelist = "";
for (var i = 0; i < items.length; i++)
{
$scope.items[i] = { "name": read_prop(items[i], 'office_desc'), "guid": read_prop(items[i], 'office_guid') };
}
$scope.reloadPage = function () { window.location.reload(); }
$scope.getResult = function ($index, item) {
var obj = {
'officeID' : '123',
'officeName' : 'Sample'
}
var result = ApiCall.PostApiCall("Login", "ChangeOffice", obj).success(function (data) {
var data = $.parseJSON(JSON.parse(data));
$scope.message = data;
});
};
}]);
I keep getting this error "PostApiCall" is not defined on browser console.
Any idea what am I doing wrong here?
Thanks.
User promise, return when $http are done:
this.PostApiCall = function (controllerName, methodName, obj) {
debugger;
var deferred = $q.defer();
$http.post('api/' + controllerName + '/' + methodName,obj).success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
};
var result = ApiCall.PostApiCall("Login", "ChangeOffice", obj).then(function (data) {
var data = $.parseJSON(JSON.parse(data));
$scope.message = data;
});
Well, I managed to fix it, I noticed two issues with my code:
I was using $http in two different places, and I was using success at both the spots. (solution suggested by charlietfl)
The other issue was that the parameters that I was passing, they were not right.
This is my updated working code:
var app = angular.module('BMSApp', []);
app.factory('ApiCall', ['$http', function ($http) {
var PostApiCall = function (controllerName, methodName) {
return $http.post(controllerName + '/' + methodName);
};
var GetApiCall = function (controllerName, methodName) {
return $http.get(controllerName + '/' + methodName);
};
return {
PostApiCall: PostApiCall,
GetApiCall: GetApiCall
};
}]);
app.controller('NationalityCtrl', ['ApiCall', '$scope', function (ApiCall,$scope) {
$scope.items = [];
var items = populateListFromLocalStorage("offices", "Login/GetOffices", 24);
var officelist = "";
for (var i = 0; i < items.length; i++)
{
$scope.items[i] = { "name": read_prop(items[i], 'office_desc'), "guid": read_prop(items[i], 'office_guid') };
}
$scope.getResult = function ($index, item) {
var result = ApiCall.PostApiCall("Login", "ChangeOffice/?officeID=" + $scope.items[$index].guid + "&officeName="+$scope.items[$index].name).then(function (data) {
$scope.reloadPage();
});
};
}]);
Thanks everyone for the help.
I programme an application in ASP.NET MVC6, angularjs and Bootstap.
I want reload a page after bootstrap modal closing.
To do this, I use $window.location.href but it's undefined.
This is my method in angular Controller:
angular
.module('LSapp')
.controller('CustomersCtrl', CustomersCtrl);
CustomersCtrl.$inject = ['$scope', '$http', '$location', '$modal', '$templateCache', '$window'];
function CustomersCtrl($scope, $http, $location, $modal, $window) {
$scope.edit = function(id)
{
var customer = getCustomer(id);
console.log('Customer => FirstName : ' + customer.FirstName);
var reqEditCustomer = $http({ url: '/api/customers/', dataType: 'json', method: 'PUT', data: JSON.stringify(customer), contentType: 'application/json; charset=utf-8' });
reqEditCustomer.success(function (dataResult) {
$scope.customer = dataResult;
$scope.cancel();
});
$scope.customers = getListCustomers();
$window.location.href = '/';
}
}
All runs except the redirection.
I hope someone can help me . Any help is welcome.
you can use
$location.path('/');
instead of
$window.location.href = '/';
Try This -
$location.path('/').replace();
if(!$scope.$$phase) $scope.$apply()
I tried to redirect since a view and not a modal. It's work.
So I think it's redirect with my modal who create problem.
It's my full controller:
(function () {
'use strict';
angular
.module('LSapp')
.controller('CustomersCtrl', CustomersCtrl)
.controller('CustomersGetCtrl', CustomersGetCtrl);
CustomersCtrl.$inject = ['$scope', '$http', '$location', '$modal', '$templateCache', '$window'];
function CustomersCtrl($scope, $http, $location, $modal, $window) {
/*---------------------------------------------------------------------------------
* Obtain Customer List
*--------------------------------------------------------------------------------*/
function getListCustomers()
{
var reqCustomers = $http.get('/api/Customers');
reqCustomers.success(function (dataResult) {
$scope.customers = dataResult;
});
return $scope.customers;
}
getListCustomers();
/*---------------------------------------------------------------------------------
* Obtain Customer by ID
*--------------------------------------------------------------------------------*/
function getCustomer(id) {
var reqGetCustomer = $http({ url: '/api/customers/' + id, method: 'GET' });
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
})
return $scope.customer;
}
$scope.edit = function(id)
{
var customer = getCustomer(id);
console.log('Customer => FirstName : ' + customer.FirstName);
var reqEditCustomer = $http({ url: '/api/customers/', dataType: 'json', method: 'PUT', data: JSON.stringify(customer), contentType: 'application/json; charset=utf-8' });
reqEditCustomer.success(function (dataResult) {
$scope.customer = dataResult;
$scope.cancel();
});
$scope.customers = getListCustomers();
//This is that I tried to redirect
//$window.location.href = '/';
//$location.path('/').replace();
//if(!$scope.$phase) $scope.$apply
}
/*---------------------------------------------------------------------------------
* Manage Customer Details Modal
*--------------------------------------------------------------------------------*/
$scope.openDetails = function (id) {
var modalInstance = $modal.open({
templateUrl: 'Modals/Customers/details.html',
controller: $scope.modalDetails,
resolve: {
id: function () {
return id
}
}
});
}
$scope.modalDetails = function($scope, $modalInstance, id)
{
if (angular.isDefined(id)) {
var reqGetCustomer = $http({ url: '/api/Customers/' + id, method: 'GET' });
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
});
} else { alert('id is undefined'); }
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
}
}
/*---------------------------------------------------------------------------------
* Manage Customer Edit Modal
*--------------------------------------------------------------------------------*/
$scope.openEdit = function (id) {
var modalInstance = $modal.open({
templateUrl: 'Modals/Customers/edit.html',
controller: $scope.modalEdit,
resolve: {
id: function () {
return id
}
}
});
}
$scope.modalEdit = function ($scope, $modalInstance, id) {
if (angular.isDefined(id)) {
var reqGetCustomer = $http({ url: '/api/Customers/' + id, method: 'GET' });
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
});
} else { alert('id is undefined'); }
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
}
}
}
//Controller to redirect since View
CustomersGetCtrl.$inject = ['$scope', '$http', '$routeParams', '$window'];
function CustomersGetCtrl($scope, $http, $routeParams, $window)
{
function getCustomer()
{
var reqGetCustomer = $http({ url: '/api/customers/' + $routeParams.id, method: 'GET' })
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
})
}
getCustomer();
$scope.edit = function () {
$window.location.href = '/';
}
}
})();
I solved the problem by using ui.router instead of ng -router.
I have a jsonp call to a server which returns an object containing two objects.
At the moment I make the jsonp call with jQuery because I've just started learning AngularJS and I dont know how it's done.
I want to use data.filters in navController and data.results in contentController
What would be the correct way to achieve this with AngularJS ?
(function($, angular) {
$(function() {
$.ajax({
jsonp: "JSONPCallback",
url: 'myUrl',
dataType: 'jsonp',
success: function(data) {
//data = {"filters":{...},"results":{...}}
}
});
});
var app = angular.module('app', []);
var controllers = {};
controllers.navController = function($scope) {
$scope.filters = [{}];
};
controllers.contentController = function($scope) {
$scope.results = [{}];
};
app.controller(controllers);
})(jQuery, angular);
Hi please see here http://plnkr.co/edit/hYkkQ6WctjhYs8w7I8sT?p=preview
var app = angular.module('plunker', []);
app.service('dataService', function($http){
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
var dataReady= false
var filters = [];
var results = [];
function getData() {
if (dataReady)
retrun
else
{
$http.jsonp(url)
.success(function(data){
//in your case
//angular.copy(data.filters, filters)
//angular.copy(data.results , results )
angular.copy(data.posts[0], results);
angular.copy(data.posts[1], filters);
dataReady = true
}).error(function(){
alert('cant load data');
});
}
}
return {
filters : filters,
results : results,
getData : getData
}
})
app.controller('MainCtrl', function($scope,dataService) {
$scope.name = 'World';
$scope.items = dataService.results;
dataService.getData();
});
app.controller('SecondCtrl', function($scope,dataService) {
$scope.filters = dataService.filters;
dataService.getData();
});