I'm working on a Themeforest-Template,where the controllers looks like this:
(function () {
"use strict";
angular.module("app.tables", []).controller("articlesCtrl", ["$scope", "$http",
function ($scope, $http) {
$http.get('www/articles.php?method=fetchAll').success(function (data) {
$scope.articles = data;
console.log($scope.articles);
}).
error(function (data) {
// log error
})
}
])}.call(this))
Everywhere in the web I find guides and tutorials where the controllers looks like this:
app.factory('articlesFactory', function ($http, $resource) {
$http.get('www/articles.php?method=fetchAll').success(function (data) {
return $resource(data);
});
app.controller('articlesCtrl', function ($scope, articlesFactory) {
$scope.articles = articlesFactory.query();
})});
why does this not work for me ?
my app.js looks like this:
(function () {
'use strict';
angular.module('app', [
'ngRoute',
'ngAnimate',
'ui.bootstrap',
'easypiechart',
'textAngular',
'ui.tree',
'ngMap',
'ngTagsInput',
'app.controllers',
'app.directives',
'app.directives',
'app.localization',
'app.nav',
'app.ui.ctrls',
'app.ui.directives',
'app.ui.services',
'app.ui.map',
'app.form.validation',
'app.ui.form.ctrls',
'app.ui.form.directives',
'app.tables',
'app.task',
'app.chart.ctrls',
'app.chart.directives',
'app.page.ctrls',
'app.calls',
'app.avgLic'
]).config([
'$routeProvider', function ($routeProvider) {
var routes, setRoutes;
routes = [
"calls/calls",
"calls/archive",
"calls/statistics",
"calls/sms",
"contacts/contacts",
"configurator/configurator",
"configurator/offers",
"configurator/search",
"configurator/articles",
"configurator/orders",
"configurator/distributors",
"orders/new_orders",
"orders/archive",
"avg/active_lic",
"avg/new_lic"
];
setRoutes = function (route) {
var config, url;
url = '/' + route;
config = {
templateUrl: 'views/' + route + '.html'
};
$routeProvider.when(url, config);
return $routeProvider;
};
routes.forEach(function (route) {
return setRoutes(route);
});
return $routeProvider.when('/', {
redirectTo: '/calls/calls'
}).when('/404', {
templateUrl: 'views/pages/404.html'
}).otherwise({
redirectTo: '/404'
});
}
]);}).call(this);
Related
I'm trying to do a simple app with ionic framework to learn how to use Firebase and manipulate data. I did everything, but my console is showing nothing. I cannot run my controller. Does anyone know what is happening?
I injected everything, at least I think I did. I guess the error is in the resolve. Is there anyone that can save me with this, please?
Here's my Controller:
(function(){
'use strict';
angular
.module('hsAdmin.users')
.controller('UsersCtrl', UsersCtrl);
UsersCtrl.$inject = ['$scope', '$state','Users' ];
function UsersCtrl($scope, $state,Users ){
var vm = angular.extend(this, {
ChangeState: ChangeState,
Users:Users
});
function ChangeState(state){
$state.go(state);
}
}
})();
Here's my Module:
(function(){
'use strict';
angular
.module('hsAdmin.users', [
'ionic',
'ngCordova',
'hsAdmin.users'
])
.config(function($stateProvider) {
$stateProvider
.state('app.users', {
url: '/users',
views: {
'menuContent': {
templateUrl: 'templates/users/users.html',
controller: 'UsersCtrl as vm'
}
}
,resolve:{
Users: function(UsersService) {
return UsersService.GetUsers().$loaded().then(function(user){
return user;
}).catch(function(error){
console.log('Error when get users: ' + error);
})
}
}
});
})
})();
Here's my Service
(function(){
'use strict';
angular
.module('hsAdmin.users')
.factory('UsersService', UsersService);
UsersService.$inject = ['fb', '$firebaseArray', '$firebaseObject','$q','$rootScope'];
function UsersService(fb, $firebaseArray, $firebaseObject,$q,$rootScope){
var service = {
GetUsers:GetUsers,
GetUsersById:GetUsersById
};
return service;
function GetUsers(){
var query = fb.child('/users');
return $firebaseArray(query);
}
function GetUsersById(id){
var query = fb.child('/users/' + id);
return $firebaseObject(query).$loaded();
}
}
})();
You are creating your hsAdmin.users module and then injecting it into itself, that is likely what is causing your problem. Try the below:
(function(){
'use strict';
angular
.module('hsAdmin.users', [
'ionic',
'ngCordova',
// 'hsAdmin.users'
])
.config(function($stateProvider) {
$stateProvider
.state('app.users', {
url: '/users',
views: {
'menuContent': {
templateUrl: 'templates/users/users.html',
controller: 'UsersCtrl as vm'
}
}
,resolve:{
Users: function(UsersService) {
return UsersService.GetUsers().$loaded().then(function(user){
return user;
}).catch(function(error){
console.log('Error when get users: ' + error);
})
}
}
});
})
})();
Try to implement controller in following way.
(function() {
'use strict';
var UsersCtrl = function($scope, $state, Users) {
var vm = angular.extend(this, {
ChangeState: ChangeState,
Users: Users
});
function ChangeState(state) {
$state.go(state);
}
}
UsersCtrl.$inject = ['$scope', '$state', 'Users'];
angular.module('hsAdmin.users').controller('UsersCtrl', UsersCtrl);
})();
This is app.states.js:
angular.module('fuelComparatorApp', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/404');
$urlRouterProvider.when('', '/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'app/components/home/views/home.view.html',
controller: "homeController",
controllerAs: 'ctrl'
})
.state('404', {
url: '/404',
templateUrl: 'app/shared/404.html'
});
}]);
And this is home.services.js:
(function () {
'use strict';
angular.module('fuelComparatorApp.homeServices', []).service('sayHelloService', sayHelloService);
sayHelloService.$inject = ['$http', '$q'];
function sayHelloService() {
function sayHi() {
console.log("hi from home service");
}
}
})();
home.controller.js
(function () {
'use strict';
angular.module('fuelComparatorApp').controller('homeController', homeController);
homeController.$inject = ["$scope", "$http", "$window", "$q", "sayHelloService"];
function homeController($scope, $http, $window, $q, sayHelloService) {
const vm = this;
vm.fuelComparatorService = sayHelloService;
sayHelloService;
return vm;
}
})();
Inside the index.html there is the usual ng-app="fuelComparatorApp" and home.view.html which utilises ng-controller="homeController" directive.
There are no errors, just the index.html doesn't show a anything from home.view.html as if I missed something somewhere.
Turned out this was missing from the index.html
<div ui-view></div>
This is specific to ui-router.
Why $location.url( "/messages" ); is not working? is there any restriction about $location inside a factory in AngularJS? any idea what is going on?
If I'm doing something wrong can you please tell my how should I redirect to another url "/messages"? I can't reload the page using so $window is not an option.
Thanks
My factory:
(function () {
'use strict';
angular
.module('app.conversation')
.factory('conversationFactory', conversation);
conversation.$inject = ['$rootScope', '$q', 'authFactory', '$location'];
function conversation($rootScope, $q, authFactory, $location) {
var service = {
changeLocation: changeLocation
};
return service;
function changeLocation() {
$location.url( "/messages" ); // recarga MIERDA!!!!!
}
}
})();
Route works fine:
(function () {
'use strict';
angular
.module('app.messages')
.config(configFunction);
configFunction.$inject = ['$routeProvider'];
function configFunction($routeProvider) {
$routeProvider
.when('/messages', {
templateUrl: 'app/messages/messages.html',
controller: 'messagesController',
controllerAs: 'meC',
resolve: {
user: function ($q, $timeout, authFactory) {
return authFactory.isLoggedInPromise();
}
}
}).when('/compose/:to?', {
templateUrl: 'app/messages/compose.html',
controller: 'composeController',
controllerAs: 'mcC',
resolve: {
user: function ($q, $timeout, authFactory) {
return authFactory.isLoggedInPromise();
}
}
});
}
})();
use $location.path( "/messages" );
I did:
$location.path( "/messages" ); // and then
$rootScope.$apply()
$location.path doesn't change in a factory with AngularJS
I can't figure out how to destroy my cache to get a new list from my server.
When I get the first list, it's work perfect, but after inserting informations to my database and sending another get to my server, the browser only show the cached version of my list, without the new data.
I tried to use cacheFactory like this:
$cacheFactory.get('$http').removeAll();
but it doesn't worked.
Here is my angular Module, Service and Controller.
Module myApp
var app = angular.module('myApp', ['ngRoute', 'LocalStorageModule', 'angular-loading-bar', 'smart-table']);
app.config(function ($routeProvider) {
$routeProvider.when("/home", {
controller: "homeController",
templateUrl: "/web/views/home.html"
});
$routeProvider.when("/cidades", {
controller: "cidadesController",
templateUrl: "/web/views/basico/cidades/cidades.html"
});
$routeProvider.otherwise({ redirectTo: "/home" });
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptorService');
});
app.run(['authService', function (authService) {
authService.fillAuthData();
}]);
cidadesService
'use strict';
app.factory('cidadesService', ['$http', '$cacheFactory', function ($http, $cacheFactory) {
var serviceBase = 'http://localhost:22207/';
var serviceFactory = {};
var _getCidades = function () {
$cacheFactory.get('$http').removeAll(); //This doesn't worked
return $http.get(serviceBase + 'api/cidades/getall').then(function (results) {
return results;
});
};
serviceFactory.getCidades = _getCidades;
return serviceFactory;
}]);
cidadesController
'use strict';
app.controller('cidadesController', ['$scope', 'cidadesService', function ($scope, service) {
$scope.cidade = {
id: "",
nome:"",
};
$scope.message = "";
$scope.getCidades = function () {
service.getCidades().then(function (results) {
$scope.cidades = [];
$scope.collection = [];
$scope.cidades = results.data;
$scope.collection = [].concat($scope.cidades);
}, function (err) {
$scope.message = err.error_description;
});
};
//Initializing the list
$scope.getCidades();
}]);
I really don't see anything wrong, but in any case you can add unique param for your request to prevent caching
like
$http.get(serviceBase + 'api/cidades/getall?unique=' + new Date().getTime())
How can I call/access Controller method ($scope.some_function()) after finished Ajax request!
var app = angular.module('home', ['ngRoute']);
app.controller('IModalCtrl', function ($scope, $http, $route, $routeParams, $location) {
$scope.will_call_this = function() {
//
};
});
app.config(['$routeProvider', '$locationProvider', '$httpProvider',
function ($routeProvider, $locationProvider, $httpProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/news/:cat/:slug/:id', {
templateUrl: function (attr) {
return '/news/' + attr.cat + '/' + attr.slug + '/' + attr.id + '?ajax=1'
},
controller: 'IModalCtrl'
// IS ANY PROPERTY/METHOD HERE
// WHICH WILL ALLOW/ACCESS TO CONTROLLER PROPERTY
})
.otherwise('/');
}]);
In above, I want to call IModalCtrl's $scope.will_call_this() function after $routeProvider has finished the request. Just like jQuery ajax work.
jQuery Ajax e.g:
jQuery.ajax("example.php")
.done(function () {
alert("success");
// Need this functionality in AngulaJS
})
.fail(function () {
alert("error");
})
.always(function () {
alert("complete");
});
Please try with the following.
app.controller('IModalCtrl', function ($scope,$rootScope, $http, $route, $routeParams, $location) {
$scope.will_call_this = function() {
//
};
$rootScope.$on('$routeChangeSuccess', function (event, next, current) {
$scope.will_call_this();
});
});