angular $scope data will not changed - angularjs

My problem is that I have a $scope.page on to different controllers under the same module.
the $scope.page data should change for each route.
I'm trying to understand this...
some code:
hall.config(function ($routeProvider) {
$routeProvider.when("/", { controller: 'pageForsideController', templateUrl: "pages/forside.html" })
.when("/om", { controller: 'pageOmController', templateUrl: "pages/omMig.html" })
.otherwise({ redirectTo: '/' })
});
hall.controller('pageOmController', function ($scope, siteData) {
siteData.getServices(function (data) {
$scope.services = data;
})
siteData.getPageByName("Mig", function (data) {
$scope.page = data;
});
});
hall.controller('pageForsideController', function ($scope, siteData) {
siteData.getPageByName("Forside", function (data) {
$scope.page = data;
});
});
hall.factory("siteData", function ($http) {
return {
getServices: function (successcb) {
$http({ method: 'GET', url: 'data.json' })
.success(function (data, status, headers, confic) {
successcb(data.services);
console.log("getServices")
});
},
getPageByName: function (name, successcb) {
$http({ method: 'GET', url: 'data.json' })
.success(function (data, status, headers, confic) {
for (var i = 0; i < data.pages.length; i++)
if (data.pages[i].title == name)
successcb(data.pages[i]);
});
}
}
});
Updated:
here is a plunker
http://plnkr.co/edit/9K3C3ahi5WMPeKLeL318?p=preview

The OP fixed the problem by following charlieftl's instructions, and removing the controller from either markup or $routeProvider.

Related

separated controller from component

Component:
crudModule.js
var crudModule = angular.module('crudModule', ['ui.router', 'smart-table', 'ngCookies', 'ui.bootstrap', 'angularModalService', 'dialogs', 'remoteValidation']);
angular.module('crudModule').component('applicationInfo', {
templateUrl: 'infoApplication.html',
controller: 'applicationInfoCtrl'
});
applicationInfoCtrl.js:
var crudModule = angular.module('crudModule')
crudModule.controller('applicationInfoCtrl', ['httpService', '$scope', function($http, $scope, $cookies, $stateParams, httpService) {
httpService.httpGetRequest("http://localhost:8080/applications/" + $stateParams.id).then(function success(response) {
$scope.application = response.data;
});
$scope.getApiKey = function () {
httpService.httpGetRequest('http://localhost:8080/applications/generateApiKey').then(function success(response) {
$scope.application.apikey = response.data.apikey;
$scope.application.apisecret = response.data.apisecret
})
};
$scope.send = function (object, url) {
httpService.httpPostRequest(object, url + "/" + $stateParams.id).catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
}).then(function success(response){
});
}
}]);
httpService.js:
var crudModule = angular.module('crudModule')
crudModule.factory('httpService', function($http) {
return {
httpGetRequest: function (url) {
return $http({
method: 'GET',
url: url
})
},
httpPostRequest: function (object, url){
return $http({
method:'POST',
url: url,
data: object
})
}
}
});
I am getting error:
Cannot read property 'httpGetRequest' of undefined.
I have injected my httpService and i dont find any mistakes yet
The problem is the order of parameters in your controller, it should be
crudModule.controller('applicationInfoCtrl', ['$http','httpService', '$scope','$cookies','$stateParams' function(http,httpService, $scope,$cookies,$stateParams) {
}

Server calls for every View Redirect(Change) in AngularJS

I have an usual AngularJS Controller:
controllers.UController = function ($scope, uFactory) {
$scope.data1 = uFactory.getDataUsingAjax1();
$scope.data2 = uFactory.getDataUsingAjax2();
$scope.data3 = uFactory.getDataUsingAjax3();
...
}
The mentioned fields (data1 - data3) gets populated using Ajax call.
I also have several Views.
When I run my app the first time, I can see all the 3 Ajax calls in order to populate data1-data3.
But every time I redirect to another View, I can see that this population starts again and again.
In my understanding it's not really a SPA architecture or it's a bad SPA.
Is this how it should work or I am missing something?
Here are the details:
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'UController',
templateUrl: '/Partial/View1.html'
})
.when('/View2',
{
controller: 'UController',
templateUrl: '/Partial/View2.html'
})
.otherwise({ redirectTo: '/View3' });
}]);
myApp.factory('uFactory', function () {
var factory = {};
data1 = [];
data2 = [];
factory.getAjaxData1 = function () {
$.ajax({
url: url,
type: 'GET',
contentType: "application/json",
async: false,
success: function (result) {
data1= result;
}
});
return data1;
}
factory.getAjaxData2 = function () {
$.ajax({
url: url,
type: 'GET',
contentType: "application/json",
async: false,
success: function (result) {
data2= result;
}
});
return data2;
}
}
var controllers = {};
controllers.uController = function ($scope, $location, uFactory) {
$scope.data1 = uFactory.getAjaxData1();
$scope.data2 = uFactory.getAjaxData2();
}
Redirection is done by href link:
a href="#/View1"Do it/a

Angular bindings not updating within $interval and $http

I've tried different variations of $apply() and $digest() to no avail.
The binding should update once the courier is no longer null with the name of the courier, however nothing is happening. I've been able to log the name of the courier when they are assigned, however the dom element is not updating. I'm using jade and compiling to html without any issues elsewhere in the application. I'm also calling the refreshDelivery function immediately prior to rendering the view shown below, which is working correctly.
app.js:
var storeController = require('./controllers/controller');
var storeApp = angular.module('AngularStore', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/store', {
templateUrl: 'views/store.html',
controller: storeController }).
when('/products/:productSku', {
templateUrl: 'views/product.html',
controller: storeController }).
when('/cart', {
templateUrl: 'views/shoppingCart.html',
controller: storeController }).
when('/delivery', {
templateUrl: 'views/delivery.html',
controller: storeController }).
otherwise({
redirectTo: '/store' });
}])
.controller('storeController', storeController);
controller.js:
function storeController($scope, $routeParams, $http, $interval, DataService) {
// get store and cart from service
$scope.store = DataService.store;
$scope.cart = DataService.cart;
$scope.mapInit = DataService.mapInit;
// use routing to pick the selected product
if ($routeParams.productSku != null) {
$scope.product = $scope.store.getProduct($routeParams.productSku);
}
// var locationOptions = {
// enableHighAccuracy: true,
// timeout: 5000,
// maximumAge: 0
// }
// navigator.geolocation.getCurrentPosition(function(pos){
// var mapOptions = {
// center: { lat: pos.coords.latitude, lng: pos.coords.longitude},
// zoom: 13
// };
// var map = new google.maps.Map(document.getElementById('map'),
// mapOptions);
// });
$scope.search = function(query){
var responseObject;
console.log('in search');
$http({
url:'/apiCall',
data: {data: '/products?keyword=' + query + '&latlong=36.125962,-115.211263'},
method: 'POST'
})
.then(function(response){
responseObject = response.data.data;
responseObject.forEach(function(data){
var productData = {
sku: data.Id.SkuPartNumber,
productName: data.Description.Name,
desc: data.Description.BrandName,
price: data.Price.DisplayPrice,
url: data.Description.ImageURL,
storeNumber: data.StoreNumber
}
var temp = new product(productData)
$scope.store.addProduct(temp)
});
});
}
$scope.getDeliveryQuote = function(){
var responseObject;
$scope.quoted = false;
var storeNumber = $scope.cart.items[0].storeNumber
console.log($scope.cart.items[0].storeNumber);
var url = '/delivery_quote?drop_off_latlong=36.125962,-115.211263&pickup_store_number='.concat(storeNumber);
$http({
url: '/apiCall/',
data: {data: url},
method: 'POST'
})
.then(function(response){
$scope.quoted = true;
console.log(response.data.id);
$scope.quote = response.data.fee;
$scope.quoteId = response.data.id
})
}
$scope.submitOrder = function(){
var url = '/submit_delivery?drop_off_latlong=36.125962,-115.211263&pickup_store_number=0001709&manifest=puppies&phone_number=555-555-5555&quote_id=' + $scope.quoteId + '&customer_name=Arnold';
$http({
url: '/apiCall/',
data: {data: url},
method: 'POST'
})
.then(function(response){
console.log(response);
$scope.deliveryId = response.data.id;
$scope.refreshDelivery();
window.location.href='/#/delivery';
})
}
$scope.refreshDelivery = function() {
var url = '/update?delivery_id='.concat($scope.deliveryId);
var promise = $interval(function(){
$http({
url: '/apiCall/',
data: {data: url},
method: 'POST'
})
.then(function(resp) {
$scope.update = resp.data;
if (resp.data.courier){
$scope.update.courier = resp.data.courier;
console.log($scope.update.courier.name);//outputs correct name
$scope.$apply();
}
//stops when complete
if ($scope.update.complete){
$interval.cancel(promise);
}
})
}, 5000 );
}
}
module.exports = storeController;
Jade before compiling to HTML:
Partial:
p.text-info {{update.courier.name}} is on their way!
Default:
html(ng-app='AngularStore')
head
// includes for jquery, angular, and bootstrap
script(src="https://maps.googleapis.com/maps/api/js?sensor=false")
script(src='bower_components/jquery/dist/jquery.min.js')
script(rel='stylesheet' href='bower_components/bootstrap/dist/css/bootstrap.min.css')
script(src='bower_components/angular/angular.js')
script(src='bower_components/angular-route/angular-route.js')
// includes for the Angular Store app
script(src='/js/main.js')
script(src='/js/bundle.js')
link(href='/styles/main.css', rel='stylesheet', type='text/css')
|
body
.container-fluid
.row-fluid
.span10.offset1
h1.well
a(href='default.html')
| Angular Store
div(ng-view='')
I found a way around the $scope issue by creating a separate controller to handle updates.
app:
var storeController = require('./controllers/storeController'),
deliveryController = require('./controllers/deliveryController');
var storeApp = angular.module('AngularStore', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/store', {
templateUrl: 'views/store.html',
controller: storeController }).
when('/products/:productSku', {
templateUrl: 'views/product.html',
controller: storeController }).
when('/cart', {
templateUrl: 'views/shoppingCart.html',
controller: storeController }).
when('/delivery/:id', {
templateUrl: 'views/delivery.html',
controller: deliveryController }).
otherwise({
redirectTo: '/store' });
}])
.controller('storeController', storeController);
new deliveryController
function deliveryController($scope, $routeParams, $http, $interval) {
console.log($routeParams);
var refreshDelivery = function(id) {
var url = '/update?delivery_id='.concat(id);
var promise = $interval(function(){
$http({
url: '/apiCall/',
data: {data: url},
method: 'POST'
})
.then(function(resp) {
$scope.update = resp.data;
if (resp.data.courier){
$scope.update.courier = resp.data.courier;
console.log($scope.update.courier.name);//outputs correct name
}
//stops when complete
if ($scope.update.complete){
$interval.cancel(promise);
}
})
}, 5000 );
}
refreshDelivery($routeParams.id);
}
module.exports = deliveryController;

Angular how to get route id at resolve block?

How can i get "pageid" inside resolve block?
For every url change i had to request the server, along with the "pageid"?
My code:
app.config(function($routeProvider){
$routeProvider
.when('/mainpage/:pageid',
{
controller:'ContentController',
resolve: {
data: function ($q, $http) {
console.log(window.location.hash)
var deferred = $q.defer();
$http({method: 'GET', url: mainURL}).then(function(data) {
deferred.resolve(data);
});
return deferred.promise;
}
},
templateUrl : 'app/partials/masterTemplate.html'
})
.otherwise({redirectTo:'/mainpage/home'});
});
You can do it like this:
data: function ($http, $routeParams) {
return $http({
method: 'GET',
url: mainURL,
params: {
pageid: $routeParams.pageid
}
})
.then(function(data) {
return data;
});
}

AngularJS $http is not defined

I'm pretty new to with AngularJS. When I'm calling $http.get I get a $http is not defined error.
This is the content of my Module:
var demoApp = angular.module('demoApp', []);
demoApp.config(function ($routeProvider) {
$routeProvider.
when('/view1',
{
controller: 'SimpleController',
templateUrl: 'View1.html'
}).
when('/view2',
{
controller: 'SimpleController',
templateUrl: 'View2.html'
})
.otherwise({ redirectTo: '/view1' });
});
demoApp.factory('simpleFactory', function () {
var factory = {};
factory.getAnnounces = function ($http) {
$http.post("http://localhost:57034/Announce/GetAllAnnounces")
.success(function (data, status, headers, config) {
return data;
}).error(function (data, status, headers, config) {
return status;
});
};
return factory;
});
demoApp.controller('SimpleController', function ($scope,simpleFactory) {
$scope.announces = [];
init();
function init()
{
$scope.announces= simpleFactory.getAnnounces();
}
});
What am I missing here? Cheers.
You need to review your code as follows:
demoApp.factory('simpleFactory', ['$http', function ($http) {
return {
getAnnounces: function () {
$http.post("http://localhost:57034/Announce/GetAllAnnounces")
.success(function (data, status, headers, config) {
return data;
}).error(function (data, status, headers, config) {
return status;
});
}
};
}]);
There's no need to pass the $http variable in the getAnnounces method definition, because it is defined already in the scope of the factory function.
I am using parameter aliasing for AngularJS in order to avoid issues with minifiers, see 'A note on minification' on the AngularJS web site.
Note anyway that $http.post.success and $http.post.error are asynchronous and you won't be able to get the data unless you're using promises ($q), see here. Therefore you could change the code this way:
demoApp.factory('simpleFactory', ['$http', '$q', function ($http, $q) {
return {
getAnnounces: function () {
var deferred = $q.defer();
$http.post("http://localhost:57034/Announce/GetAllAnnounces")
.success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
}
};
}]);
And in the SimpleController:
demoApp.controller('SimpleController', ['simpleFactory', '$scope', function (simpleFactory, $scope) {
$scope.announces = [];
simpleFactory.getAnnounces()
.then(function(data) {
// call was successful
$scope.announces = data;
}, function(data) {
// call returned an error
$scope.announces = data;
});
}]);

Resources