k[$c].maps.Load is not a function - angularjs

I want to load a map with pins stored in json file in angular app.
but i'm facing with this error!
k[$c].maps.Load is not a function
appControllers.controller('mapController', function($scope, $http) {
$http.get("data/markers.json").success(function(data) {
$scope.offices = data;
$scope.insertGoogleScript();
});
$scope.insertGoogleScript = function() {
var script = document.createElement("script");
script.src = "http://maps.googleapis.com/maps/api/js?callback=loaded";
document.getElementById('mainMap').appendChild(script);
}
$scope.loadMap = function() {
angular.forEach($scope.offices, function(office) {
console.log('#');
});
}
});
function loaded() {
var appElement = document.querySelector('[ng-controller="mapController"]');
var $scope = angular.element(appElement).scope();
$scope.$apply(function() {
$scope.loadMap();
});
}

Related

Angular $injector:unpr] Unknown provider:

Working through a test app with a service and I keep getting an error about adding the service using the factory method. Not sure why, i know i am probably staring right at the problem..
The error i get is:
VM497 angular.js:10126 Error: [$injector:unpr] Unknown provider: githubProvider <- github
http://errors.angularjs.org/1.2.28/$injector/unpr?p0=githubProvider%20%3C-%20github
Thanks in advance.
(function() {
var github = function($http) {
var getUser = function(username) {
return $http.get('https://api.github.com/users/' + username).then(function(response) {
return response.data
});
};
var getRepos = function(user) {
return $http.get(user.repos_url).then(function(response) {
return response.data;
});
};
return {
getUser: getUser,
getRepos: getRepos
};
};
var module = angular.module("githubViewer");
module.factory('github', github) ;
});
Controller that injects the service
// Code goes here
(function() {
var app = angular.module("githubviewer", []);
var MainController = function(
$scope, github, $interval,
$log, $anchorScroll, $location) {
var onUserComplete = function(data) {
$scope.user = data;
github.getRepos($scope.user).then(onRepos, onError);
};
var onRepos = function(data){
$scope.repos = data;
$location.hash("userDetails");
$anchorScroll();
}
var onError = function(reason) {
$scope.error = "Could not fetch the Data";
};
var decrementCountDown = function(){
$scope.countdown -= 1;
if($scope.countdown < 1){
$scope.search($scope.username);
}
};
var countDownInterval = null;
var startCountDown = function(){
countDownInterval = $interval(decrementCountDown, 1000, $scope.countdown);
};
$scope.search = function(username){
$log.info("Searching for: " + username);
github.getUser(userName).then(onUserComplete, onError);
if (countDownInterval) {
$interval.cancel(countDownInterval);
}
};
$scope.username = "angular";
$scope.message = "GitHub Viewer";
$scope.repoSortOrder = "-stargazers_count";
$scope.countdown = 5;
startCountDown();
};
app.controller("MainController", MainController)
}());
You need to inject the service into app, from the code you posted. you are not injecting anything into the module.
var app = angular.module("githubviewer", ['yourservice', function(yourservice){}]);
This should get you headed in the right direction.
found my problem, the name of my module had a typo on capitalization. The V in Viewer was wrong.
Controller - var app = angular.module("githubviewer", []);
Service - var module = angular.module("githubViewer");

How to load data from a factory service before using in application

This is an ASP.NET MVC app with AngularJS.
When the application loads, we have to call some action method which returns a dictionary of resources, string key string value.
This array/dictionary of resources, needs to be available throughout the application.
How can we wait until these resources are loaded before accessing them within the application?
var app = angular.module("app", []);
app.controller("TestCtrl", ['cacheService', function (cacheService) {
var self = this;
self.test = function () {
var value = cacheService.getResourceValue('Err_lbl_UserExist');
}
}]);
app.factory('cacheService', ['$http', function ($http) {
var obj = {};
obj.resourceDictionary = [];
obj.loadResourceDictionary = function () {
var httpConfig = {
url: "/Cache/GetResourceDictionary",
method: "GET",
headers: {
"X-Requested-With": 'XMLHttpRequest',
"__RequestVerificationToken": $("[name=__RequestVerificationToken]").val()
}
}
$http(httpConfig)
.success(function (data) {
obj.resourceDictionary = data;
});
}
obj.getResourceValue = function (resourceKeyName) {
if (obj.resourceDictionary.length <= 0) {
obj.loadResourceDictionary();
}
return obj.resourceDictionary[resourceKeyName];
}
return obj;
}]);
EDIT w/ Accepted Answer
var app = angular.module("app", []);
app.controller("TestCtrl", ['cacheService', function (cacheService) {
var self = this;
self.test = function () {
var value = cacheService.getResourceValue('Err_lbl_UserExist');
}
}]);
app.factory('cacheService', ['$rootScope', '$http', function ($rootScope, $http, $q) {
var obj = { resourcesLoaded: false };
obj.loadResourceDictionary = function () {
obj.resourcesLoaded = false;
var httpConfig = {
url: "Cache/GetResourceDictionary",
method: "GET",
headers: {
"X-Requested-With": 'XMLHttpRequest',
"__RequestVerificationToken": $("[name=__RequestVerificationToken]").val()
}
}
$http(httpConfig).success(function (data) {
obj.resourceDictionary = data;
obj.resourcesLoaded = true;
$rootScope.$broadcast("ResourcesLoaded", null);
});
}
obj.getResourceValue = function (resourceKeyName) {
if (!obj.resourcesLoaded) {
obj.loadResourceDictionary();
$rootScope.$on("ResourcesLoaded", function () {
return obj.resourceDictionary[resourceKeyName];
});
} else {
return obj.resourceDictionary[resourceKeyName];
}
}
return obj;
}]);
you could use broadcast and on for that.
So once your keys are loaded you fire an event using broadcast
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$broadcast
you listen for that message wherever you need to using on :
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$on
you can store the data in a service, this will make it a singleton and you can reuse it, all you have to do is inject the service in whatever controller you need.

AngularJS add new rows from Database

I have an app which fetches data from a database on load.
Since the data in the database changes every few seconds, I would like to dynamically add the new data in the database into the table in the HTML page.
Any ideas on how to implement without reloading the controller?
The current code:
app.js
var app = angular.module('myApp', ['ui.bootstrap','countTo']);
app.filter('startFrom', function() {
return function(input, start) {
if(input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
app.config(['$compileProvider', function($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|http?|file|data):/);
}]);
app.controller('customersCrtl', function ($scope, $http, $timeout) {
$scope.$emit('LOAD');
$scope.progressBar = { progress : 0 };
$http.get('ajax/getCustomers.php').success(function(data){
$scope.list = data;
$scope.currentPage = 1; //current page
$scope.entryLimit = 50; //max no of items to display in a page
$scope.filteredItems = $scope.list.length; //Initially for no filter
$scope.totalItems = $scope.list.length;
$scope.$emit('UNLOAD');
});
(function progress(){
if($scope.progressBar.progress < 100){
$timeout(function(){
$scope.progressBar.progress += 1;
progress();
},5);
}
})();
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
});
app.controller('delayController',['$scope',function($scope){
$scope.$on('LOAD',function(){$scope.loading=true});
$scope.$on('UNLOAD',function(){$scope.loading=false});
}]);
app.controller("PostsCtrl", function($scope, $http, $timeout) {
$scope.progressBarScanned = { progressScanned : 0 };
(function tick() {
$http.get('ajax/scanStatus.php').
then(function(response) {
$scope.posts = response.data;
$scope.scanProgerss = $scope.posts[0].isScanning;
$scope.scanPercentage = $scope.posts[0].scanPercentage;
$scope.timeToFinish = $scope.posts[0].timeToFinish;
$scope.amountScanned = $scope.posts[0].amountScanned;
$scope.totalItemsToScan = $scope.posts[0].totalItemsToScan;
$scope.avgScanTimePerItem = $scope.posts[0].avgScanTimePerItem;
});
$timeout(tick, 1000);
})();
(function progressScanned(scanned){
if($scope.scanPercentage < 100){
$timeout(function(){
$scope.progressScanned.progress = 1;
progressScanned();
},5);
}
})();
});
//Modal
var ModalDemoCtrl = function ($scope, $modal) {
$scope.open = function (imageKey) {
$modal.open({
templateUrl: 'myModalContent.html',
backdrop: true,
windowClass: 'full',
controller: function ($scope, $modalInstance, data, imageKey) {
$scope.data='';
$scope.data = data;
$scope.getImage = function () {
return $scope.data[imageKey];
}
$scope.cancel = function () {
$modalInstance.dismiss('close');
};
},
resolve: {
data: function() {
// access outer controller scope by using $scope.$parent
return $scope.$parent.data;
},
imageKey: function() {
return imageKey;
}
}
});
}};

Using $http in a controller in AngularJS

I have an AngularJS 1.2 app. My app has a controller that looks like this:
myApp.controller('MyController', ['$scope', '$rootScope', '$http',
function ($scope, $rootScope, $http) {
$scope.newItem_Click = function () {
var modalInstance = $modal.open({
templateUrl: 'item-dialog.html',
size: 'md',
controller: function ($scope, $modalInstance) {
$scope.item = { typeId: 7, id: '-1' };
$scope.saveItem = function (did) {
if ($scope.item.description) {
if ($scope.item.description.trim().length > 0) {
$scope.item.departmentId = did;
$modalInstance.close($scope.item);
}
} else {
alert('Please enter your description.');
}
};
$scope.cancelItem = function () {
$modalInstance.dismiss('cancel');
};
$scope.getItems = function (departmentId) {
var url = '/api/items?departmentId=' + departmentId;
return $http.get(url).then(
function (response) {
var results = response.data;
results.reverse();
var items = [];
var i = 0;
angular.forEach(results, function (item, key) {
var local = results[i].CreatedUTC;
results[i].CreatedOn = new Date(local);
items.push(item);
i = i + 1;
});
console.log(items);
$scope.items = items;
}
);
};
$scope.$on('list-updated', function () {
$scope.getItems($scope.item.id);
});
}
});
modalInstance.result.then(
function (item) {
var apiUrl = '/api/items';
apiUrl = apiUrl + '?typeId=' + item.typeId;
if (item.departmentId!== '-1') {
apiUrl = apiUrl + '&departmentId=' + item.departmentId;
}
apiUrl = apiUrl + '&content=' + item.description;
apiUrl = encodeURI(apiUrl);
$http.post(apiUrl).then(
function () {
$rootScope.$broadcast('list-updated');
}
);
}
);
};
}]);
For some reason, I can successfully save an item. The console.log(items) statement displays all of the items as I would expect. However, my view is not being updated. What am I doing wrong? I suspect its because I'm assigning $scope.items inside of the HTTP response. Yet, I'm not sure how to get around it.
I know this is not recommended. However, I am in crunch mode.

Angular global factory

I created a factory that I would like to use in different pages:
var sessionApp = angular.module('sessionApp', ['LocalStorageModule']);
sessionApp.config(function(localStorageServiceProvider)
{
localStorageServiceProvider
.setPrefix('mystorage')
.setStorageType('localStorage');
});
sessionApp.factory('SessionFactory', function(localStorageService)
{
var service = {};
var _store = 'session';
service.load = function()
{
var session = localStorageService.get(_store);
}
service.save = function(data)
{
localStorageService.set(_store, JSON.stringify(data));
}
service.delete = function()
{
localStorageService.remove(_store);
}
return service;
});
Then I would add it on apps run method where I would assign it to the $rootScope. I left that part of the code commented out for now.
var loginApp = angular.module("loginApp", []);
loginApp.run(function($rootScope, SessionFactory)
{
//$rootScope.sessionFactory = SessionFactory;
$rootScope.$on('$routeChangeStart',
function(ev, next, current)
{
});
});
My error is:
Unknown provider: SessionFactoryProvider <- SessionFactory
Is it because my factory is from sessionApp and my login module is loginApp? Does that mean that I need to have the variables named the same like below:
File: login.js
var myApp = angular.module("loginApp", []);
myApp.run(function($rootScope, SessionFactory)
{
//$rootScope.sessionFactory = SessionFactory;
$rootScope.$on('$routeChangeStart',
function(ev, next, current)
{
});
});
File: session.js
myApp.config(function(localStorageServiceProvider)
{
localStorageServiceProvider
.setPrefix('mystorage')
.setStorageType('localStorage');
});
myApp.factory('SessionFactory', function(localStorageService)
{
var service = {};
var _store = 'session';
service.load = function()
{
var session = localStorageService.get(_store);
}
service.save = function(data)
{
localStorageService.set(_store, JSON.stringify(data));
}
service.delete = function()
{
localStorageService.remove(_store);
}
return service;
});
The array argument to angular.module is an array of other modules that you new module depends on. loginApp needs to list sessionApp as a dependency.
var loginApp = angular.module("loginApp", ["sessionApp"]);

Resources