I'm relatively new to angularjs. I'm trying to work with this some JSON and can't seem to figure out the issue with my post command. The get works just fine, but anything else throws a 404 url error though I checked and everything matches.
Here is my app.js code which calls the get command that works
angular
.module('app', [
'ui.router'
])
.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/home.html',
controller: 'homeCtrl',
resolve: {
friends: ['$http', function($http){
return $http.get('./api/friends.json').then(function(response ){
return response.data;
})
}]
}
})
.state('about', {
url: '/about',
templateUrl: 'templates/about.html',
controller: 'aboutCtrl'
})
.state('contact', {
url: '/contact',
templateUrl: 'templates/contact.html'
})
}])
Here is the homeCtrl.js file which loads stuff for the home page, where I want to edit the contents of the home page and post back to the JSON file.
Here I call the post and it gives me a 404 error.
angular
.module('app')
.controller('homeCtrl', ['$scope', 'friends', '$http', function($scope, friends, $http){
$scope.title = "Home";
$scope.friends = friends;
$scope.items =['item1', 'item2','item3'];
$scope.selectedValue = 'item1';
$scope.save = function() {
$http.post('./api/friends.json', friends);
};
}]);
This is the home.html
<h1>{{title}}</h1>
<ul>
<li ng-repeat = "friend in friends">
<input type="text" ng-model="friend.name">
<input type="text" ng-model="friend.age">
</li>
</ul>
<button ng-click="save()" class="btn btn-primary">Save</button>
This is the code for friends.json
[
{"name": "Will", "age": 30},
{"name": "Laura", "age": 25}
]
You said "I want to edit the contents of the home page and post back to the JSON file."
You cant save to the local files with angular. "Get" request is working just because browser can load static file (its same with css or html).
You definitely run application just by clicking html and not in any http-server. If you run server (for example nodejs http-server) in the folder and connect browser to it. It will not provide 404 (but of course it will not update json file)
If you need data to be saved, you need real working application which will provide API and process request and store data.
Related
I have an AngularJS application. I recently added couple of routes but they don't work. The rest is working fine.
I included them in my index.html
<script src="privacy_policy/privacy_policy.js"></script>
<script src="contacts/contacts.js"></script>
I added them in my app.js file:
angular.module('myApp', [
...
'myApp.privacy_policy',
'myApp.contacts',
...
]).
The route system:
$routeProvider.when('/privacy_policy', {
templateurl: 'privacy_policy/privacy_policy.html',
data: {
needauth: false
}
});
$routeProvider.when('/contacts', {
templateurl: 'contacts/contacts.html',
data: {
needauth: false
}
});
I added a simple controller:
'use strict';
angular.module(
'myApp.privacy_policy', ['ngRoute']
).
config(['$routeProvider', function($routeProvider) {
}]).
controller('PrivacyPolicyCtrl', ["$scope", "$http", "store", "URL", function($scope, $http, store, URL) {
}]);
And some simple html:
<div ng-controller="PrivacyPolicyCtrl" class='row below-header'>
PRIVACY POLICY
</div>
Finally I created a simple link to that view:
<li><a href='/privacy_policy'>Privacy policy</a></li>
I created the SAME things for contacts but if I click on those link ng-view is completely empty.
All the others route are working fine and I can't see any difference. I get no error on the console.
In the route system in app.js If I put a different template, for example:
$routeProvider.when('/privacy_policy', {
templateurl: 'faq/faq.html',
data: {
needauth: false
}
});
The faq page is diplayed correctly. What am I missing?
Ok I finally find you what the problem is.
I only needed to change this:
templateurl: 'contacts/contacts.html',
with this:
templateUrl: 'contacts/contacts.html',
I am creating two page webapp using AngularJS.
my Json file is:
{
"data": [
{ "name": "bhav",
"id": 123
},
{"name": "bhavi",
"id": 1234
},
{"name": "bhavk",
"id": 1235
}
]
}
my app.js(Routing file is):
myApp = angular.module('myApp', ['slickCarousel',
'ngRoute',
'myAppControllers',
'myAppServices','swipeLi'
]);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home-page.html',
controller: 'ProfileListCtrl',
}).
when('/profile/:typeofprofile', {
templateUrl: 'partials/profile-detail.html',
controller: 'ProfileDetailCtrl'
})
}]);
and my 1st page(home-page.html) is in given formate:
<div ng-repeat="data in data">
{{data.name}}
</div>
and on 2nd page(profile-details.html)
I want that id number of that profile considering I am using http.get request to pull data from Json file in controllers.
so please help me to fetch the id or name of clicked profile without passing through URL .
Note: I already look through ui-route link: Angular ui router passing data between states without URL but I didnt get that.
As you stated in the comments, you want to use $state.go() to pass your data.Using $state.go() to pass params is pretty simple as well. You need to inject ui.router in your application. I have created 2 partial views to show the passing of params where the params are passed from header.html to side.html.
Your JS will be something like below:
var app = angular.module('nested', ['ui.router']);
app.config(function($stateProvider,$locationProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider.state('top', {
url: "",
templateUrl: "header.html",
controller: 'topCtrl'
})
.state('top.side', {
url: '/app/:obj/:name',
templateUrl: "side.html",
controller: 'filterCtrl'
})
});
app.controller('topCtrl', function($scope,$state) {
$scope.goItem = function(){
$state.go('top.side',{obj:441,name:'alex'});
};
});
app.controller('filterCtrl', function($scope,$state) {
console.log(JSON.stringify($state.params));
$scope.params = $state.params;
});
Here is the working PLUNKER where you will find what you need to do regarding the views, controller and script:
http://plnkr.co/edit/M1QEYrmNcwTeFd6FtC4t?p=preview
I have provided the methods to pass $stateParams using both ui-sref and $state.go(). However, if you want to share the data among all the controllers. see my answer in this question:
Share Data in AngularJs
I use ui-router angular js file for routing and its not working when used in a complex scenario. I have posted all my code in Plunker for your view and thanks in advance for your time and help.
"use strict";
var app = angular.module( "productManagement", ["ui.router", "common.services", "productResourceMock"] );
app.config([ "$stateProvider", "$urlRouterProvider",
function($stateProvider, $urlRouterProvider){
// Redirect to home view when route not found
$urlRouterProvider.otherwise("/");
$stateProvider
// Home state routing
.state("home", {
url: "/",
templateUrl: "route-welcome.html"
})
.state("productList", {
url: "/products",
templateUrl: "route-productlist.html"
})
.state("productDetail", {
url: "/products/detail/:productId",
templateUrl: "route-productdetail.html"
})
}
]);
Plunker link here
Your requests for template pages are being caught by the $httpBackend, which doesn't know about your .html files. It is instead throwing errors like the following:
Error: Unexpected request: GET route-welcome.html
No more request expected
To fix this, you can add a passThrough to your app.run:
....
$httpBackend.whenGET(productUrl).respond(products);
$httpBackend.whenGET(/\.html$/).passThrough();
....
I have an Angular app which makes some calls (POST and GET for now) to a backend service (powered by node.js with a REST interface). While developing the app itself I noticed it makes two requests to the backend each time a button is pressed or a page is loaded. Curiously everything works but each time I press some button the backend gets two requests. I am not using any fancy package only ngRoute, ngResource and routeStyles for css partials. Anybody has an idea of what could be the reason why the app behaves like that?
I actually found another question similar to this one but the OP there was using express aside of Angular and there is no answer...
EDIT added some code.
in app.js:
'use strict';
var cacheBustSuffix = Date.now();
angular.module('myApp', ['myApp.controllers', 'myApp.services', 'myApp.filters', 'ngRoute', 'ngResource', 'routeStyles'])
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$locationProvider
.html5Mode({enabled: true,
requireBase: false})
.hashPrefix('!');
$routeProvider
.when('/', {redirectTo: '/myApp'})
.when('/myApp', {
templateUrl: '/partials/home.html?cache-bust=' + cacheBustSuffix,
controller: 'ctrlHome'
})
.when('/myApp/search', {
templateUrl: '/partials/search.html?cache-bust=' + cacheBustSuffix,
controller: 'ctrlSearch'
})
.when('/myApp/list/', {
templateUrl: '/partials/list.html?cache-bust=' + cacheBustSuffix,
controller: 'ctrlList'
})
// a bunch of other redirections
.otherwise({
templateUrl: '/partials/404.html?cache-bust=' + cacheBustSuffix,
controller: 'ctrl404'});
}]);
from services.js:
'use strict';
var app = angular.module('myApp.services', ['ngResource']).
factory('List', function ($resource) {
return $resource(WSROOT + '/search', {}, {get: {method: 'GET', isArray: false}});
});
from controllers.js, one controller that makes multiple requests
var controllers = angular.module('myApp.controllers', []);
var ctrlList = controllers.controller('ctrlList', function ($scope, $window, List) {
$window.document.title = 'myApp - List';
List.get({}, function (data) {
// $scope.res is an array of objects
$scope.res = data.response;
$scope.nitems = data.response.length;
});
});
ctrlList.$inject = ['$scope', 'List'];
And the network call when loading the index+home and navigating to some other page. As you can see, it first loads the index page, the scripts and styles listed there (not shown), then the home where I have a controller similar to the one above and suddenly two wild request to my web server:
Can we see your HTML files? I had this problem a while back. My solution was that by declaring a controller in the routing, and in the pages, a double post was created as each controller was loaded twice.
//Home
.state('tab.home', {
url: '/home',
views: {
'tab-home': {
templateUrl: 'templates/tab-home.html',
controller: 'HomeCtrl' // <-- This goes away
}
}
})
I am having this strange issue with only one of my views. The problem is that whenever I reload it by refreshing (Cmd + R / F5) the browser the whole app doesn't work until I change the route (manually or by clicking a link). The view resolves some data before it renders and I can verify that there are no request to the server whatsoever. Basically when I refresh I see all my scripts are loaded but my controller is never called (had a console.log in there) and I never get the view rendered.
Here is the state
$stateProvider.state( 'purchases', {
url: '/purchases',
views: {
"main": {
controller: 'PurchasesCtrl',
templateUrl: 'purchases/purchases.tpl.html'
}
},
resolve: {
purchases: function(PurchasesService, $rootScope) {
return PurchasesService.getPurchasesForUser($rootScope.user._id);
}
},
data:{ pageTitle: 'Purchases' }
});
$stateProvider.state( 'purchases_buy', {
url: '/purchases/buy/{itemId:[0-9a-fA-F]{24}}',
views: {
"main": {
controller: 'PurchasesBuyCtrl',
templateUrl: 'purchases/purchases_buy.tpl.html'
}
},
resolve:{
item: function(ItemsService, $stateParams){
return ItemsService.getItem($stateParams.itemId);
}
},
data:{ pageTitle: 'Buy' }
});
And here is the controller:
.controller( 'PurchasesCtrl', ['$scope', 'PurchasesService', '$stateParams', 'purchases', function ( $scope, PurchasesService, $stateParams, purchases ) {
$scope.purchases = purchases.data;
console.log("loaded");
$scope.predicates = ['firstName', 'lastName', 'birthDate', 'balance', 'email'];
$scope.selectedPredicate = $scope.predicates[0];
}])
.controller( 'PurchasesViewCtrl', ['$scope', 'PurchasesService', '$stateParams', 'purchase', function ( $scope, PurchasesService, $stateParams, purchase ) {
$scope.purchase = purchase.data;
}])
I have no idea why it keeps doing this but it is annoying and I would like to know what is the problem.
This is not an issue with UI-Router, but rather than server related issue wherein when you refresh your browser it doesn't point back to the index.html
So you'll need to host your page in an Apache environment and create a redirection such as creating an .htaccess file
I have this as an issue before, you can trace back my ticket from Github
The difference only is that I use Grunt to serve my app then I created an .htaccess along with my index.html
here's an .htaccess gist that I used for solving this issue. link