Angularjs text / data not showing up - javascript

I am building a very basic angular app to learn. My app basically loads a list of users and prints them all out on the home page with a checkbox next to each name and also displays the number of present users.
The list of users appears to work - I have 11 users and 11 checkboxes show up. HOWEVER, the actual text doesn't show up. The users.length variable also shows up as empty too.
Here is my core.js file:
var userApp = angular.module('userApp', []);
userApp.controller("mainController", mainController);
function mainController($scope, $http) {
$scope.formData = [];
// when landing on the page, get all users and show them
$http.get('/api/users')
.success(function(data) {
$scope.users = data;
console.log(data);
console.log(data.length);
})
.error(function(data) {
console.log('Error: ' + data);
});
// when submitting the add form, send the text to the node API
$scope.createUser = function() {
$http.post('/api/users', $scope.formData)
.success(function(data) {
$scope.formData = {} //clear the form so our user is ready to enter another user
$scope.users = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}
And here is my index.html file:
<html ng-app="userApp">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<title>Node/Angular Todo App</title>
<!-- SCROLLS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"><!-- load bootstrap -->
<style>
html { overflow-y:scroll; }
body { padding-top:50px; }
</style>
<!-- SPELLS -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script><!-- load angular -->
<script src="core.js"></script>
</head>
<body ng-controller="mainController">
<div class="container">
<div class="jumbotron text-center">
<h1>Users Count: <span class="label label-info"> {{ users.length }}</span></h1>
</div>
<div id="user-list" class="row">
<div class="col-sm-4 col-sm-offset-4">
<!-- loop over users -->
<div class="checkbox" ng-repeat="user in users">
<label>
<input type="checkbox">{{ user.first_name }}
</label>
</div>
</div>
</div>
<!-- create users -->
<div id="user-form" class="row">
<div class="col-sm-8 col-sm-offset-2 text-center">
<form>
<div class="form-group">
<!-- BIND THIS VALUE TO formData.text IN ANGULAR -->
<input type="text" class="form-control input-lg text-center" placeholder="I want to buy a puppy that will love me forever" ng-model="formData.text">
</div>
<!-- createUser() WILL CREATE NEW USERS -->
<button type="submit" class="btn btn-primary btn-lg" ng-click="createUser()">Add</button>
</form>
</div>
</div>
</div>
</body>
</html>
Sample user record:
{
"id": 1,
"first_name": "Bruce",
"last_name": "Lee",
"email": "blee#email.com",
"password": "blee",
"created_at": "2016-01-08T21:49:18.337Z",
"updated_at": "2016-01-08T21:49:18.337Z"
},
The data also properly console.log()'s.
Can someone help?
Thanks in advance!

If you want to take over user data to Angular, you should fix {{ first_name }} to {{ user.first_name }} in your html.
It means that each label get name from not globally declared but user.
Moreover you should better register controller in your js code.
in core.js
userApp.controller("mainController", mainController);

The $http service for angular should return a response object and not the raw data. According to the docs this is what is in this object:
The response object has these properties:
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
```
Try assigning data.data to the $scope.users variable like so:
$http.get('/api/users')
.success(function(data) {
$scope.users = data.data; // <-------- here!!! (consider calling it response so you can use 'response.data'
console.log(data);
console.log(data.length);
})
.error(function(data) {
console.log('Error: ' + data);
});
Quick edit: it also seems like you are using the old way of doing things (.success and .error). The service returns a promise and you should be consuming it with .then.
Example
$http
.get('/api/users')
.then(function(response) {
$scope.users = response.data;
}, function(error) {
console.log('Error: ' + error);
});

Related

Second AJAX call not functioning

Last Update
I realized why I was getting undefined when I created the result2 variable I set it to undefined instead of let result2 = ''; setting it to a string. Once I made that adjustment the undefined went away. Final script.js is below.
Update 4
It finally works it came down to the following line which was incorrect document.querySelectorAll("weathers").innerHTML = result2; I had to go back and change weathers to an id and not a class and I had to change the line above to document.querySelector("#weathers").innerHTML += result2; and now it works. I just have to figure out on my own why I get an undefined in my code see image.
Update 3
I am down to my last portion which is I get the results I want if I console log my results which look like this:
With this line I am not getting anything in my html document.querySelectorAll("weathers").innerHTML = result2; I am going to try something else to see if I could get this to work. If you notice though I am getting an undefined in my code in the image does anyone know if that impacts why I am not getting any output? I get no error messages either.
UPDATE 2
I made the adjustments to eliminate too much code the updates code will just be in my script.js file listed below. I get the following output which is an array of objects:
When I run the code I get the following error message:
Uncaught TypeError: Cannot read property 'name' of undefined
at XMLHttpRequest.xhr2.onload (script.js:57) xhr2.onload # script.js:57 load (async) loadWeathers # script.js:33
I am going to work on the correct syntax to extract the information I need since it is now an array of objects and not just an object.
UPDATE 1
With a suggestion below I was able to finally get something to work off of. Now I can see that instead of giving me one city at a time it is putting all of the cities inside of the api request url and I get the following error message:
script.js:77 GET
http://api.openweathermap.org/data/2.5/weather?q=San_Francisco,Miami,New_Orleans,Chicago,New_York_City&APPID=XXXXXXXX
404 (Not Found)
Background:
I am learning about API's and am building a mini weather web app. I am learning the long way Vanilla Javascript before I move onto doing the same thing in Jquery.
Goal:
I would like to have two things going on at once:
When a user inputs a name of a city a card will pop up with weather information.
When a user visits the page there will be already about five major cities populated on the page like so:
What I have so far:
So far I have been able to build the functionality for the input so when a user inputs the name of the city a card will pop up on the page and looks like this:
I also have some code to get into the next topic which is my problem.
Problem:
I have added a second ajax call that contains an array of cities that will be added to the URL. I have added a second button ("Get Weathers") for testing purposes that when I click on the button all of the cities will pop up like in the first image. I have done some research but everything I find involves jquery and not vanilla javascript Ajax. I cannot figure out why nothing is populating. I have checked the console for errors and I am not getting any. When I check the network traffic I am not getting any call requests. I am not getting anything and I cannot figure out why.
Here is my html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<LINK REL=StyleSheet HREF="style.css" TYPE="text/css">
<title>Current Weather App</title>
</head>
<body>
<main role="main">
<section class="jumbotron text-center">
<div class="container">
<h1 class="jumbotron-heading">Today's Weather</h1>
<p class="lead text-muted">Curious about weather in your location? Just fill in below and submit.</p>
<p>
<div class="input-group mb-3">
<input type="text" class="form-control" id="city">
<div class="input-group-append">
<button class="btn btn-outline-secondary" id="buttonW" type="button">Get Weather</button>
<button class="btn btn-outline-secondary" id="buttonW2" type="button">Get Weathers</button>
</div>
</div>
</p>
</div>
</section>
<div id="weather"></div>
<div class="album py-5 bg-light">
<div class="container">
<div class="row" id="weathers"></div>
</div>
</div>
</main>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
</script>
<script src="script.js"></script>
</body>
</html>
Here is my FINAL script.js file:
// Create an event listener
document.getElementById("buttonW").addEventListener("click", loadWeather);
document.getElementById("buttonW2").addEventListener("click", loadWeathers);
///////////////THIS IS PART OF THE loadWeathers///////////////////////////////////////////////////////////////////////////////////////////
function getCity(locations) {
for (let i = 0; i < locations.length; i++) {
}
return locations;
}
function loadWeathers() {
let xhr2 = new XMLHttpRequest();
const cities = [
"5368361",
"4173495",
"4335045",
"4887398",
"5128638"
];
const base_path2 =
"http://api.openweathermap.org/data/2.5/group?id=" + getCity(cities) + "&APPID=XXXXXXXXXXXXXXXXXXXXXX";
xhr2.open("GET", base_path2, true);
xhr2.onload = function () {
if (this.status == 200) {
let cityWeathers2;
try {
cityWeathers2 = JSON.parse(this.responseText);
} catch (e) {
// JSON not valid, show error message
}
console.log(cityWeathers2)
// //add weather info
for (let i = 0; i < cities.length; i++) {
let result2 = '';
result2 +=
`<div class="col-md-4">
<div class="card mb-4 box-shadow">
<div class="card-body">
<h5 class="card-title">${cityWeathers2.list[i].name}</h5>
<p class="card-text">Here are some weather details for your City</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">Weather: ${cityWeathers2.list[i].weather[0].main} <img class="card-img-top weather-icon" src="${getIconURL(cityWeathers2.list[i].weather[0].icon)}" alt="Card image cap"></li>
<li class="list-group-item">Temperature: ${convertKtoF(cityWeathers2.list[i].main.temp) }° </li>
<li class="list-group-item">Wind Speed: ${convertMPStoMPH(cityWeathers2.list[i].wind.speed) } </li>
<li class="list-group-item">Geo Location: ${cityWeathers2.list[i].coord.lat} , ${cityWeathers2.list[i].coord.lon}</li>
</ul>
</div>`
// console.log(result2)
document.querySelector("#weathers").innerHTML += result2;
}
}
}
xhr2.send();
}
function loadWeather() {
// console.log(city);
let xhr = new XMLHttpRequest();
const city = document.getElementById("city").value;
const base_path =
"http://api.openweathermap.org/data/2.5/weather?q=" + city + "&APPID=XXXXXXXXXXXXXXXXXXXXXXX";
xhr.open("GET", base_path, true);
xhr.onload = function () {
// const city = document.getElementById("city").value;
if (this.status == 200) {
let cityWeathers;
try {
cityWeathers = JSON.parse(this.responseText);
} catch (e) {
// JSON not valid, show error message
}
const result =
`<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">${cityWeathers.name}</h5>
<p class="card-text">Here are some weather details for your City</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">Weather: ${cityWeathers.weather[0].main} <img class="card-img-top weather-icon" src="${getIconURL(cityWeathers.weather[0].icon)}" alt="Card image cap"></li>
<li class="list-group-item">Temperature: ${convertKtoF(cityWeathers.main.temp) }° </li>
<li class="list-group-item">Wind Speed: ${convertMPStoMPH(cityWeathers.wind.speed) } </li>
<li class="list-group-item">Geo Location: ${cityWeathers.coord.lat} , ${cityWeathers.coord.lon}</li>
</ul>
</div>`;
document.getElementById("weather").innerHTML = result;
}
}
xhr.send();
}
// Convert from Kelvins to Fahrenheit
function convertKtoF(kelvin) {
return Math.round((kelvin - 273.15) * 1.8);
}
// Convert from Meters Per Second to Miles Per Hour
function convertMPStoMPH(mps) {
return (Math.round(10 * mps * 2.2369362920544) / 10) + " mph";
}
// Weather icon
function getIconURL(icon) {
return "https://openweathermap.org/img/w/" + icon + ".png";
}
Any guidance or suggestions would be greatly appreciated!
I can't speak to the accuracy of the request (per comments), but the problem is xhr2.send(); is within the body of your xhr2.onload function.
For multiple cities, you may need to use city Ids, see https://openweathermap.org/current#severalid. The docs don't seem to mention multiple cities by name as you are attempting to do.

AngularJs Filter: Generating notArray errors

I'm having an issue with a filter in my angularJS project.
We have a simple draft feature that allows users to save the contents of a large form as a JSON string in our database. They then can go to a section of the site to display and continue working on these forms. I want to provide them a filter on that page to filter by the date they saved the draft on.
Here is my markup:
<div ng-controller="savedFormCtrl" ng-cloak id="saved-form-wrapper"
class="border border-dark border-top-0 border-right-1 border-bottom-1
border-left-1 px-0" ng-init="getSavedForms()"
>
<!-- Search filters -->
<form name="savedFormsFilterWrapper" layout="row" flex="35" layout-align="end center" class="toolbar-search">
<!-- Date filter -->
<md-input-container flex="80">
<div class="text-light font-weight-bold float-left">Filter by saved date:</div>
<md-tooltip style="font-size:1em;">Filter your saved HRTF's</md-tooltip>
<md-datepicker name="dateFilter" class="hrtf-date savedFilterDatepicker"
md-date-locale="myLocale" data-ng-model="savedFormFilters" ng-blur="setFilterDate()"
md-placeholder="" md-open-on-focus
aria-label="Saved forms date filter">
</md-datepicker>
</md-input-container>
</form>
<!-- Saved forms body -->
<div id="savedFormAcc" class="accordion col-md-12 pt-3">
<!-- Accordion item Header -->
<div class="card" ng-repeat="item in savedForms | filter:savedFormFilters">
<div class="card-header savedFormItem" id="savedForm{{$index}}" data-toggle="collapse" data-target="#collapse{{$index}}">
<md-button class="md-raised md-primary" data-toggle="collapse"
data-target="#collapse{{$index}}" aria-expanded="false"
aria-controls="collapse{{index}}"
>
Form Saved on {{ item.savedOn }} - Click to expand
</md-button>
</div>
<!-- Accordion body continues on below -->
</div>
</div>
And my JS:
(function () {
'use strict';
angular.module('hrtf')
.controller('savedFormCtrl', ['$scope', '$window', 'formService',
function savedFormCtrl($scope, $window, formService) {
$scope.savedFormFilters = '';
//Get users's saved forms
$scope.savedForms = {};
$scope.getSavedForms = function(){
formService.getSavedForms()
.then(saved => {
saved.forEach( item =>{
item.data_json = JSON.parse(item.data_json);
});
$scope.savedForms = saved;
return $scope.savedForms;
};
}
]);
})();
Now, the filter works. But whenever The page is loaded, anywhere from 20-50 errors appear, all with the contents Error: [filter:notarray] Expected array but received: {}
All I need to do here is provide a simple filter on a string value to the parent objects savedOn: xxData Herexx value.
What am I doing wrong?
Turns out, I had a similar issue to this post
Basically, my ng-repeat and filter were initializing before the associated model could load. Initializing the model as a blank array and then creating the filter as part of the promise chain did the trick:
//Get users's saved forms
$scope.savedForms = [];
$scope.getSavedForms = function(){
formService.getSavedForms()
.then(saved => {
//Convert and format items here
$scope.savedForms = saved;
$scope.savedFormFilters = { savedOn: ''};
return $scope.savedForms;
}).catch(e => { console.error(e);
});
};
Pretty basic, but I'll leave it here in case it helps someone in the future :)

How to send image as input to django view using angular frontend?

I have an existing django web api with angular frontend, using which i can upload images and display them to the user.Now i want to extend this.On clicking the button "segment"(see image) it should pass the corresponding image to my python script on the backend, which does some processing on the image.
I have my python script in the views.py file of the main app,which is some thing like this:
from django.shortcuts import render
def segment_image(request):
if request.method == 'GET':
form = segment_form()
else:
if form.is_valid():
info = request.POST['info_name']
output = script_function(info)
''' Here i am calling script_function,passing the POST data info to it'''
return render(request, 'your_app/your_template.html', {
'output': output,
})
return render(request, 'your_app/your_template.html', {
'form': form,
})
'''here info is our image in some format'''
def script_function(info):
...
'''here goes my mian logic to process the image.'''
...
return x,y,w,h
I have never worked with images as inputs in angular,i dont know how to route the image using angularjs to my view.Now how can i implement this segmentImage() function in app.js file so that the function would call the corresponding view by passing this image as a POST argument.
Below is my index.html file.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<!-- Include Angular and several angular libraries -->
<script src="node_modules/angular/angular.min.js"></script>
<script src="node_modules/angular-resource/angular-resource.min.js"></script>
<!-- Include our app -->
<script src="js/app.js"></script>
<!-- Include our own controllers, factories, directives, etc... -->
<script src="js/filesModelDirective.js"></script>
<script src="js/images.rest.js"></script>
<!-- Include Bootstrap CSS -->
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<!-- Main Division -->
<div class="container-fluid">
<div ng-app="imageuploadFrontendApp" ng-controller="MainCtrl">
<!-- Panel for Uploading a new Image -->
<div class="panel panel-default">
<div class="panel-body">
<form class="form" name="form" ng-submit="uploadImage()">
<label for="inputFile">Select Image:</label>
<input id="inputFile" type="file" files-model="newImage.image">
<br />
<button class="btn btn-default" type="submit">
Upload
</button>
<br />
</form>
</div>
</div>
<div ng-if="images.length == 0">
There are no images available yet.
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-4" ng-repeat="image in images track by image.pk">
<h3>
Image {{ image.pk }}
<button class="btn btn-warning" ng-click="deleteImage(image)">Delete</button>
<button class="btn btn-primary" ng-click="segmentImage(image)">Segment</button>
</h3>
<a href="{{ image.image }}">
<img class="img-responsive" ng-src="{{ image.image }}">
</a>
</div>
</div>
</div>
</div>
</body>
</html>
Below is my app.js file:
// create a module called imageuploadFrontendApp, which relies on ngResource
var myApp = angular.module('imageuploadFrontendApp', ['ngResource']);
// Configure ngResource to always use trailing slashes (required for django)
myApp.config(function($resourceProvider) {
$resourceProvider.defaults.stripTrailingSlashes = false;
});
// Main Controller
myApp.controller('MainCtrl', function($scope, Images)
{
console.log('In main Control');
$scope.images = Images.query();
$scope.newImage = {};
$scope.uploadImage = function()
{
// call REST API endpoint
Images.save($scope.newImage).$promise.then(
function(response) {
// the response is a valid image, put it at the front of the images array
$scope.images.unshift(response);
},
function(rejection) {
console.log('Failed to upload image');
console.log(rejection);
}
);
};
$scope.deleteImage = function(image)
{
image.$delete(
function(response)
{
// success delete
console.log('Deleted it');
// update $scope.images
$scope.images = Images.query();
},
function(rejection)
{
console.log('Failed to delete image');
console.log(rejection);
}
);
};
});
You can try some thing like this
Define a url for your view function
urls.py
url(r'^image/script_function/$', script_function, name="script_function")
Write the view for the url script_function
views.py
def script_function(info):
...
'''here goes my mian logic to process the image.'''
...
return x,y,w,h
app.js
$scope.segmentImage = function(image){
$http({method:'POST', url:'https://127.0.0.1/image/script_function/', data:{'image': image}}).
then(function successCallback(response) {
console.log('Image Posted successfully')
},function errorCallback(response) {
console.log('Image Post failed')
}
});
};
Pass the image to the sever via post and process your image.

Can i retain old value of scope and update some other value to other div in AngualrJS

Well,I'll try to explain my approach why I am doing this. I have trimmed the code for the sake of simplicity. I want to create one div where there should be <h4>BroadCategory Name</h4> and below this headline, I am calling one API to fetch some images associated with that BroadCategory Name
<div ng-controller="NavigationController">
<div ng-repeat="primaryItems in categories">
<div>
<h4><span>{{primaryItems.BroadCategory}}</span></h4>
</div>
<div ng-init="getImgForCategory(this.primaryItems)">
<div ng-repeat="ad in ads">
{{ ad.ad_type }}
<a ng-href="#productList/{{primaryItems.BroadCategory}}">
<img src="{{ ad.images[0] }}" >
</a>
</div>
</div>
</div>
</div>
My Controller:
$http.get("/get_categories/")
.success(function(response){
$scope.categories = response;
})
.error(function (msg) {
console.log(msg);
});
$scope.getImgForCategory = function (categoryInfo) {
var category = (categoryInfo.BroadCategory);
$http.get('/Some_API_ad_type='+category) //API to fetch some images associated with that **BroadCategory**
.success(function (response) {
$scope.ads = response;
})
.error(function (msg) {
console.log(msg);
})
}
Issue : Issue is that $scope.ads keeps the value of last called API response and so the {{ ad.ad_type }} and similar ads attributes have all the same values (which is the response for the last BroadCategory name)
How can I resolve this with best Angular approach?
<h1>Expected Output: </h1>
<h4>BroadCategory1</h4>
BC1_data1
<br>BC1_data2
<h4>BroadCategory2</h4>
BC2_data1
<br>BC2_data2
<h1>Actual Output: </h1>
<h4>BroadCategory1</h4>
BC2_data1
<br>BC2_data2
<h4>BroadCategory1</h4>
BC2_data1
<br>BC2_data2
Well, the generated html in your inner ng-repeat all use the same $scope.ads list. So if that gets updated, all data on your screen will just show the new value of $scope.ads.
What I would do is link the adds to the category. Like the following:
$scope.getImgForCategory = function (categoryInfo) {
var category = (categoryInfo.BroadCategory);
$http.get('/Some_API_ad_type='+category)
.success(function (response) {
categoryInfo.ads = response;
})
.error(function (msg) {
console.log(msg);
})
}
.
<div ng-controller="NavigationController">
<div ng-repeat="primaryItems in categories">
<div>
<h4><span>{{primaryItems.BroadCategory}}</span></h4>
</div>
<div ng-init="getImgForCategory(primaryItems)">
<div ng-repeat="ad in primaryItems.ads">
{{ ad.ad_type }}
<a ng-href="#productList/{{primaryItems.BroadCategory}}">
<img src="{{ ad.images[0] }}" >
</a>
</div>
</div>

Failed to load resource: the server responded with a status of 404 (Not Found) angular js + ionic

This is the error im having from Google Devt Tools. Anyone knows the problem? I tried to change in many times including the file structure and the stateProvider (no controllers for that) in app.js file but it does not seem to be the issue. (script is included in app.js with correct file name and directory)
In addition, my logout and submitPost buttons arent working as well.
newpost.html
<div class="modal slide-in-up" ng-controller="NavCtrl">
<!-- Modal header bar -->
<header class="bar bar-header bar-secondary">
<button class="button button-clear button-primary" ng-click="close()">Cancel</button>
<h1 class="title">New Shout</h1>
<button class="button button-positive" ng-click="submitPost()">Done</button>
</header>
<!-- Modal content area -->
<ion-content class="padding has-header">
<form class ng-submit="submitPost()" ng-show="signedIn()">
<div class="form-group">
<input type="text" class="form-control" placeholder="Title" ng-model="post.title">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Link" ng-model="post.url">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</ion-content>
</div>
controller.js file
app.controller('NavCtrl', function ($scope, $firebase, $location, Post, Auth, $ionicModal) {
$scope.post = {url: 'http://', title: ''};
// Create and load the Modal
$ionicModal.fromTemplateUrl('newpost.html', function(modal) {
$scope.taskModal = modal;
}, {
scope: $scope,
animation: 'slide-in-up'
});
// Open our new task modal
$scope.submitPost = function () {
Post.create($scope.post).then(function (postId) {
$scope.post = {url: 'http://', title: ''};
$location.path('/posts/' + postId);
$scope.taskModal.show();
});
};
$scope.close = function() {
$scope.taskModal.hide();
};
$scope.logout = function () {
Auth.logout();
};
});
List of items page, post.html
<ion-header-bar class="bar-positive" ng-controller="NavCtrl">
<button class="button button-clear" ng-click="submitPost()">New</button>
<h1 class="title"><b><a class="navbar-brand" href="#/posts">MyApp</a></b></h1>
<button class="button button-clear" ng-click="logout()">Logout</button>
</ion-header-bar>
Change <base href="/"> to <base href="./"> from index.html
404 literally means that file was not found. It's simple as that. Check if the URL is right, and there are no rediretions being done(use fiddler). Perhaps the protocol should be https:// istead of http://? Perhaps you need "www" in url?
Click the url given in Chrome and see if the file exists.
Not sure if anyone is interested, but Experienced a similar problem when trying to upload to firebase storage here is how i resolved it.
The Error screenshot where upload fails with 503 and then 400 after 75% progress
The code segment I use for Upload is
//Event: data.Event,
// Date: data.Date,
// Time: data.Time
var data = getData();
data.filename=uploadfile.name;
var metadata = {
customMetadata: {
data
}
}
var storageRef = firebase.storage().ref().child("features");
console.log("Filenames to upload :" + uploadfile.name);
var fileRef = storageRef.child(uploadfile.name);
var uploadTask = fileRef.put(uploadfile,metadata);
The Problem was with custom meta data, once I changed it to like this,
var metadata = {
customMetadata: {
Event: data.Event,
Date: data.Date,
Time: data.Time
}
}
the upload started working. So, if there is an error in setting custom meta data, firebase errors out and possible does not provide that as a reason.
Screenshot of working here
successful upload once the custom meta data is corrected

Categories

Resources