Here is my controller code:
.controller('TransitCtrl', function ($ionicPlatform, $scope, $state, $q, $ionicSideMenuDelegate, $timeout, $http, design, config) {
$ionicSideMenuDelegate.canDragContent(false);
var vm = this;
vm.userImg = design.user_img;
vm.isGetStarted = false;
vm.getPV = true;
vm.getPL = false;
vm.showWelcome = false;
var counter = 1;
$ionicPlatform.ready(function(){
$timeout( function(){
var userDataStageFirst = {
url: config.baseURL + 'userDataStageFirst',
dataServer: {
serverTaskRequest: counter
}
}
var url = userDataStageFirst.url;
var dataServer = userDataStageFirst.dataServer;
$http.post(url, dataServer).success(function (data, status, headers, config) {
alert(data)
})
.error(function () {
alert("error");
});
}, 1000 );
});
})
And here is this app.js
.state('app.transit', {
url: '/transit',
views: {
'menuContent': {
templateUrl: 'templates/transit.html',
controller: 'TransitCtrl'
}
}
})
and My html page
<ion-view hide-nav-bar="true" ng-controller="TransitCtrl as vm">
<ion-content>
hello world
</ion-content>
</ion-view>
When I use $scope in place of vm its working perfectly good, but when I use vm, it sends 2 $http request to the server. Not being able to understand this concept here.
Try remove ng-controller="TransitCtrl as vm" from template.
and change to this
state('app.transit', {
url: '/transit',
views: {
'menuContent': {
templateUrl: 'templates/transit.html',
controller: 'TransitCtrl as vm'
}
}
})
Related
Right now i am making an AngularJS+UI router install application. But i have a problem, the problem is, that i want to disable access to the views, associated with the install application. I want to do it in resolve in the state config.
But the problem is i need to get the data from a RESTful API, whether the application is installed or not. I tried making the function, but it loaded the state before the $http.get request was finished.
Here was my code for the resolve function:
(function() {
var app = angular.module('states', []);
app.run(['$rootScope', '$http', function($rootScope, $http) {
$rootScope.$on('$stateChangeStart', function() {
$http.get('/api/v1/getSetupStatus').success(function(res) {
$rootScope.setupdb = res.db_setup;
$rootScope.setupuser = res.user_setup;
});
});
}]);
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/404");
$stateProvider.state('db-install', {
url: "/install/db",
templateUrl: 'admin/js/partials/db-install.html',
controller: 'DBController',
resolve: {
data: function($q, $state, $timeout, $rootScope) {
var setupStatus = $rootScope.setupdb;
var deferred = $q.defer();
$timeout(function() {
if (setupStatus === true) {
$state.go('setup-done');
deferred.reject();
} else {
deferred.resolve();
}
});
return deferred.promise;
}
}
})
.state('user-registration', {
url: "/install/user-registration",
templateUrl: "admin/js/partials/user-registration.html",
controller: "RegisterController"
})
.state('setup-done', {
url: "/install/setup-done",
templateUrl: "admin/js/partials/setup-done.html"
})
.state('404', {
url: "/404",
templateUrl: "admin/js/partials/404.html"
});
}]);
})();
EDIT:
Here is what my ajax call returns:
Try this way:
$stateProvider.state('db-install', {
url: "/install/db",
templateUrl: 'admin/js/partials/db-install.html',
controller: 'DBController',
resolve: {
setupStatus: function($q, $state, $http) {
return $http.get('/api/v1/getSetupStatus').then(function(res) {
if (res.db_setup === true) {
$state.go('setup-done');
return $q.reject();
}
return res;
});
}
}
})
Then inject setupStatus in controller:
.state('setup-done', {
url: "/install/setup-done",
templateUrl: "admin/js/partials/setup-done.html",
controller: ['$scope', 'setupStatus', function ($scope, setupStatus) {
$scope.setupdb = setupStatus.db_setup;
$scope.setupuser = setupStatus.user_setup;
}]
})
I can't seem to get my Wordpress JSON to work. I'm brand new to the AngularJS and Ionic worlds, so I've been reading and watching tutorials.
This is the relevant part of my app.js file:
(function() {
var app = angular.module('mybodyapp', ['ionic', 'angularMoment','LocalStorageModule']);
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('index', {
url : '/',
templateUrl : 'index.html',
controller : 'MainController'
});
$stateProvider.state('list', {
url: '/list',
templateUrl: 'templates/list.html'
});
$stateProvider.state('edit', {
url: '/edit/:noteId',
templateUrl: 'templates/edit.html',
controller: 'EditCtrl'
});
$stateProvider.state('add', {
url: '/add',
templateUrl: 'templates/edit.html',
controller: 'AddCtrl'
});
$stateProvider.state('notes', {
url: '/notes',
templateUrl: 'templates/notes.html'
});
$stateProvider.state('posts', {
url: '/posts',
templateUrl: 'templates/posts.html',
controller: 'PostsCtrl'
});
$urlRouterProvider.otherwise("/");
});
// ...
I am able to grab data from Reddit through a controller, but not data from Wordpress. I found a good demo template but cannot figure out how to 'rewrite' the beginning of the JS controller. I removed the top of the original angular.module('starter.controllers', []) and put angular.module('mybodyapp') followed by:
.controller('AppCtrl', function($scope, $timeout, $rootScope) {
$rootScope.url = 'http://scottbolinger.com/wp-json/wp/v2/';
})
.controller('PostsCtrl', function( $scope, $http, DataLoader, $timeout, $ionicSlideBoxDelegate, $rootScope ) {
console.log('PostsCtrl');
$scope.loadPosts = function() {
DataLoader.get( $rootScope.url + 'posts' ).then(function(response) {
$scope.posts = response.data;
console.log( response.data );
}, function(response) {
console.log('error', response);
});
}
// Load posts on page load
$scope.loadPosts();
paged = 2;
$scope.moreItems = true;
// Load more (infinite scroll)
$scope.loadMore = function() {
if( !$scope.moreItems ) {
return;
}
var pg = paged++;
$timeout(function() {
DataLoader.get( $rootScope.url + 'posts' + '?page=' + pg ).then(function(response) {
angular.forEach( response.data, function( value, key ) {
$scope.posts.push(value);
});
if( response.data.length <= 0 ) {
$scope.moreItems = false;
}
}, function(response) {
$scope.moreItems = false;
console.log('error');
});
$scope.$broadcast('scroll.infiniteScrollComplete');
$scope.$broadcast('scroll.resize');
}, 1000);
}
$scope.moreDataExists = function() {
return $scope.moreItems;
}
// Pull to refresh
$scope.doRefresh = function() {
console.log('Refreshing!');
$timeout( function() {
$scope.loadPosts();
//Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
}, 1000);
};
})
.controller('PostCtrl', function($scope, $stateParams, DataLoader, $ionicLoading, $rootScope, $sce ) {
$ionicLoading.show({
noBackdrop: true
});
var singlePostApi = $rootScope.url + 'posts/' + $stateParams.postId;
DataLoader.get( singlePostApi ).then(function(response) {
$scope.post = response.data;
// Don't strip post html
$scope.content = $sce.trustAsHtml(response.data.content.rendered);
$ionicLoading.hide();
}, function(response) {
console.log('error', response);
});
});
The name in your ng-app directive must match your module name. The name in your ng-controller directive must match your controller name.
For more information on the ng-app directive see the AngularJS ng-app API Reference.
For the ng-controller directive, AngularJS ng-controller API Reference
UPDATE
The demo you grabbed has three controllers. You need to make them methods of angular.module
angular.module('mybodyapp').controller('AppCtrl',...
angular.module('mybodyapp').controller('PostsCtrl', function( $sc
angular.module("mybodyapp").controller('PostCtrl', function($scope
I want to make my views show only after the initial data is fetched and i am trying to accomplish this with a route resolve, but i can't get it to work. What am i doing wrong? Also my angular skills are a bit shabby so i aplogize in advance if my question is dumb.
Application.js :
var Application = angular.module('ReporterApplication', ['ngRoute']);
Application.config(['$routeProvider', '$interpolateProvider',
function($routeProvider, $interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
$routeProvider
.when('/packing/scan.html', {
templateUrl: 'packing/scan.html',
controller: 'PackingScanController',
resolve: {
initData : Application.PackingScanInit()
}
})
.when('/packing/stats.html', {
templateUrl: 'packing/stats.html',
controller: 'PackingStatisticsController'
})
etc
and here is my Scan.js file :
Application.PackingScanInit = function ($q,$timeout,$http) {
var serverData = "";
$http.get('/packing/scan.action')
.success(function(data){
serverData = data;
})
.error(function(data){
serverData = data;
});
return serverData;
}
Application.controller('PackingScanController', ['initData', '$scope', '$http', function(initData, $scope, $http) {
var packer = this;
// Message log model
packer.messageLog = [{
status : "",
message : null
}];
the files are included in this order.
service are singletons means there are initialized only one but time but if you simply return from service it will be called one time but if you return a function from service it will be called again and again .See Below Sample for working.
var app = angular.module('ajay.singhApp', [])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
resolve: {
myVar: function (repoService) {
return repoService.getItems().then(function (response) {
return response.data;
});
}
}
})
.when('/view2', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/view1'
});
}]);
app.factory('repoService', function ($http) {
return {
getItems: function () {
return $http.get('TextFile.txt');
}
};
});
Try this:
Application.PackingScanInit = function ($q,$timeout,$http) {
return $http.get('/packing/scan.action')
.success(function(data){
return data;
})
.error(function(data){
return data;
});
}
Also you have to adjust your resolve to this:
resolve: {
initData : Application.PackingScanInit
}
Here is a specific working example:
(function() {
angular.module('app',['ngRoute']);
function TestCtrl($scope, initData) {
$scope.value = initData;
}
angular.module('app').config(function($routeProvider) {
$routeProvider.otherwise({
template: '`<p>Dude {{value}}</p>`',
controller: TestCtrl,
resolve: {
initData: function($http) {
return $http.get('test.json') //change to test-e.json to test error case
.then(function(resp) {
return resp.data.value; //success response
}, function() {
return 'Not Found'; // error response
});
}
}
});
});
})();
http://plnkr.co/edit/SPR3jLshcpafrALr4qZN?p=preview
I want to redirect after login to /dashboard
$scope.submit = function (user) {
if ($scope.loginForm.$valid) {
UserService.login(user).then(
function (result) {
$location.path('/dashboard');
}, function (reason) {
$scope.msg = "username or password is not correct";
});
$scope.reset();
}
};
in app.js I want to create my menu dynamically and show dashboard.html
$routeProvider
.when('/dashboard', {
templateUrl: 'views/dashboard.html',
abstract:true,
resolve: {
menu: function (MenuService) {
return MenuService.getMenu();
}
},
controller: function ($scope, menu) {
$scope.menu = menu;
$scope.oneAtATime = true;
}
})
and in dashboard I use ng-view to load my template
<div class="content">
<div class="container">
<ng-view></ng-view>
</div>
but it catch "Maximum call stack size exceeded" error.
THE MenuService servie return promise
factory('MenuService', function ($q, $http) {
var getMenu = function () {
var deferred = $q.defer();
$http.post('/menu', 1).
success(function (data) {
deferred.resolve(data);
}).
error(function (data, status) {
deferred.reject(status);
});
return deferred.promise;
};
return{
getMenu: getMenu
}
})
I changed the MenuService.getMenu() to this:
$routeProvider
.when('/dashboard', {
templateUrl: 'views/dashboard.html',
abstract:true,
resolve: {
menu: function (MenuService) {
MenuService.getMenu().then(function(result){
return result;
});
}
},
controller: function ($scope, menu) {
$scope.menu = menu;
$scope.oneAtATime = true;
}
})
and now dashboard is loaded but without menu. then method is called after dashboard.html loading!!!!
when I remove ng-view every thing work perfectly.
What is my problem?
thank you
Basically you need to do change in your custom resolve service code. Currently your controller promise has receiving chain promise, so you should return a promise instead of return chain promise.
Code
$routeProvider
.when('/dashboard', {
templateUrl: 'views/dashboard.html',
abstract:true,
resolve: {
menu: function (MenuService) {
return MenuService.getMenu();
}
},
controller: function ($scope, menu) {
menu.then(function(data){
$scope.menu = data;
});
$scope.oneAtATime = true;
}
})
the stateProvider of my app have a nested view (base.gallery -> base.gallery.detail) and if i click on a link inside my gallery it should show the detailview, but it doesn't...
the link looks good for me, but it only changes the url in the browser and it logs "get displayed" from the onEnter-function, but it doesn't display the template("modules/album/detail/view/detail.html") in my ui-view...
e.g.: for my link <a ui-sref="base.photos.detail(params(item.id))" class="list-item-link" href="/gallery/21/detail/457">
.state("base", {
abstract: true,
templateUrl: 'modules/base/views/base.html',
controller: function($scope, navigationData){
$scope.navigation.data = navigationData;
},
resolve:{
navigationData:function(navigationSvc){
var response = navigationSvc;
return response;
}
}
})
.state("base.categories", {
url: "/categories",
templateUrl: "modules/album/list/view/list.html",
controller: function($scope, data){
$scope.settings.data = data;
$scope.settings.type = "categories";
},
resolve:{
data:function(listSvc){
var response = listSvc.load("categories");
return response;
}
}
})
.state("base.category", {
url: "/category/:id",
templateUrl: "modules/album/list/view/list.html",
controller: function($scope, data){
$scope.settings.data = data;
$scope.settings.type = "galleries";
},
resolve:{
data:function($stateParams, listSvc){
var response = listSvc.load("category/"+$stateParams.id);
return response;
}
},
})
.state("base.gallery", {
url: "/gallery/:id",
templateUrl: "modules/album/list/view/list.html",
controller: function($scope, data, $stateParams){
$scope.settings.data = data;
$scope.settings.type = "photos";
},
resolve:{
data:function($stateParams, listSvc){
var response = listSvc.load("gallery/"+$stateParams.id);
return response;
}
}
})
.state("base.gallery.detail", {
url: "/detail/:photo_id",
templateUrl: "modules/album/detail/view/detail.html",
controller: function($scope, $stateParams){
console.log("doesn't get displayed ");
$scope.settings.type = "photo";
},
onEnter: function(){
console.log("get displayed");
}
})
html of my index where i load all my lists and i als want to display my detail view inside that ui-view...
...
<div class="content" ui-view></div>
...
html of my list view
<li class="list-item" ng-repeat="item in list.data">
<a ui-sref="{{state}}(params(item.id))" class="list-item-link">item.title</a>
</li>
UPDATE
k i got it ;) i need views and then use the # to target it in the same ui-view from my index.html
.state("base.gallery.detail", {
url: "/detail/:photo_id",
views:{
"#" : {
controller: function($scope, $stateParams, listSvc){
$scope.settings = {};
$scope.settings.type = "photos";
$scope.photo = listSvc.data[$stateParams.id_photo-1];
console.log($stateParams);
},
template: "<h2>detail</2><div>{{photo.title}}</div>"
}
});