AngularJS update View after Model loaded from Ajax - ajax

I'm newbie of angularjs developing and i wrote this simple app, but don't understand how i can update view, after the model il loaded from ajax request on startup!
This code don't work when I add delay into photos.php, using:
sleep(3);
for simulate remote server delay! instead if search.php is speedy it work!!
<!doctype html>
<html ng-app="photoApp">
<head>
<title>Photo Gallery</title>
</head>
<body>
<div ng-view></div>
<script src="../angular.min.js"></script>
<script>
'use strict';
var photos = []; //model
var photoAppModule = angular.module('photoApp', []);
photoAppModule.config(function($routeProvider) {
$routeProvider.when('/photos', {
templateUrl: 'photo-list.html',
controller: 'listCtrl' });
$routeProvider.otherwise({redirectTo: '/photos'});
})
.run(function($http) {
$http.get('photos.php')//load model with delay
.success(function(json) {
photos = json; ///THE PROBLEM HERE!! if photos.php is slow DON'T update the view!
});
})
.controller('listCtrl', function($scope) {
$scope.photos = photos;
});
</script>
</body>
</html>
output of photos.php
[{"file": "cat.jpg", "description": "my cat in my house"},
{"file": "house.jpg", "description": "my house"},
{"file": "sky.jpg", "description": "sky over my house"}]
photo-list.html
<ul>
<li ng-repeat="photo in photos ">
<a href="#/photos/{{ $index }}">
<img ng-src="images/thumb/{{photo.file}}" alt="{{photo.description}}" />
</a>
</li>
</ul>
EDIT 1, Defer solution:
.run(function($http, $q) {
var deferred = $q.defer();
$http.get('photos.php')//load model with delay
.success(function(json) {
console.log(json);
photos = json; ///THE PROBLEM!! if photos.php is slow DON'T update the view!
deferred.resolve(json);//THE SOLUTION!
});
photos = deferred.promise;
})
EDIT 2, Service solution:
...
//require angular-resource.min.js
angular.module('photoApp.service', ['ngResource']).factory('photoList', function($resource) {
var Res = $resource('photos.php', {},
{
query: {method:'GET', params:{}, isArray:true}
});
return Res;
});
var photoAppModule = angular.module('photoApp', ['photoApp.service']);
...
.run(function($http, photoList) {
photos = photoList.query();
})
...

The short answer is this:
.controller('listCtrl', ['$scope', '$timeout', function($scope, $timeout) {
$timeout(function () {
$scope.photos = photos;
}, 0);
}]);
The long answer is: Please don't mix regular javascript and angular like this. Re-write your code so that angular knows what's going on at all times.
var photoAppModule = angular.module('photoApp', []);
photoAppModule.config(function($routeProvider) {
$routeProvider.when('/photos', {
templateUrl: 'photo-list.html',
controller: 'listCtrl'
});
$routeProvider.otherwise({redirectTo: '/photos'});
});
photoAppModule.controller('listCtrl', ['$scope', function($scope) {
$scope.photos = {};
$http.get('photos.php') // load model with delay
.success(function(json) {
$scope.photos = json; // No more problems
});
}]);

use broadcast
//service
var mydata = [];
this.update = function(){
$http.get(url).success(function(data){
mydata = data;
broadcastMe();
});
};
this.broadcastMe = function(){
$rootScope.$broadcast('mybroadcast');
};
//controller
$scope.$on('mybroadcast', function(){
$scope.mydata = service.mydata;
};
http://bresleveloper.blogspot.co.il/
EDIT:couple of days ago i've learned the best practice
http://bresleveloper.blogspot.co.il/2013/08/breslevelopers-angularjs-tutorial.html

I think you're better off using high level angular services for data transfer, also look into promises and services:
http://docs.angularjs.org/api/ng.$q

You need to bind an element in your view to a property (simple or object) of your $scope object. Once the $scope object is updated the view should be updated on its own. That is the beauty of AngularJS.
EDIT:
Please register your controller as
photoAppModule.controller('listCtrl', function($scope){
$scope.photos = photos;
});
If photos variable is not available, then you might have to create a service with the variable and inject in the controller.

Related

How to load AJAX in react

Im trying to get my json result into my react code
The code looks like the following
_getComments() {
const commentList = "AJAX JSON GOES HERE"
return commentList.map((comment) => {
return (
<Comment
author={comment.author}
body={comment.body}
avatarUrl={comment.avatarUrl}
key={comment.id} />);
});
}
How do i fetch AJAX into this?
First, to fetch the data using AJAX, you have a few options:
The Fetch API, which will work out of the box in some browsers (you can use a polyfill to get it working in other browsers as well). See this answer for an example implementation.
A library for data fetching (which generally work in all modern browsers). Facebook recommends the following:
superagent
reqwest
react-ajax
axios
request
Next, you need to use it somewhere in your React component. Where and how you do this will depend on your specific application and component, but generally I think there's two scenarios to consider:
Fetching initial data (e.g. a list of users).
Fetching data in response to some user interaction (e.g. clicking a
button to add more users).
Fetching initial data should be done in the life-cycle method componentDidMount(). From the React Docs:
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);
Here they use jQuery to fetch the data. While that works just fine, it's probably not a good idea to use such a big library (in terms of size) to perform such a small task.
Fetching data in response to e.g. an action can be done like this:
var UserGist = React.createClass({
getInitialState: function() {
return {
users: []
};
},
componentWillUnmount: function() {
this.serverRequest && this.serverRequest.abort();
},
fetchNewUser: function () {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
var users = this.state.users
users.push(lastGist.owner.login)
this.setState({ users });
}.bind(this));
},
render: function() {
return (
<div>
{this.state.users.map(user => <div>{user}</div>)}
<button onClick={this.fetchNewUser}>Get new user</button>
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);
Lets take a look on the fetch API : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Lets say we want to fetch a simple list into our component.
export default MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
lst: []
};
this.fetchData = this.fetchData.bind(this);
}
fetchData() {
fetch('url')
.then((res) => {
return res.json();
})
.then((res) => {
this.setState({ lst: res });
});
}
}
We are fetching the data from the server, and we get the result from the service, we convert is to json, and then we set the result which will be the array in the state.
You can use jQuery.get or jQuery.ajax in componentDidMount:
import React from 'react';
export default React.createClass({
...
componentDidMount() {
$.get('your/url/here').done((loadedData) => {
this.setState({data: loadedData});
});
...
}
First I'd like to use fetchAPI now install of ajax like zepto's ajax,the render of reactjs is asyn,you can init a state in the constructor,then change the state by the data from the result of fetch.

Laracast Video(Push Events to the Client) error?

I try to create event handling...so i followed this video tutorial ..everything working perfect. but in last minute video when i try to show user name in list view its not updating in real time as list view but i checked console.log('users') each object i can get it from my console.... but in view no updates or no errors ......... what is error ?
This is video tutorial - LINK
<body>
<ul id="users">
<li v-repeat="user: users">#{{ user.name }}</li>
</ul>
<script src="https://js.pusher.com/3.0/pusher.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.20/vue.min.js"></script>
<script>
// (function () {
// var pusher = new Pusher('82355e6cc93e7a15d7d5', {
// encrypted: true
// });
//
// var channel = pusher.subscribe('test');
// channel.bind('App\\Events\\UserHasRegistered', function(data) {
// console.log(data);
// });
// })();
new Vue({
el: '#users',
data:{
users:[]
},
ready: function(){
var pusher = new Pusher('82355e6cc93e7a15d7d5', {
encrypted: true
});
pusher.subscribe('test')
.bind('App\\Events\\UserHasRegistered',this.addUser);
},
methods: {
addUser: function(user){
this.users.push(user);
}
}
})
</script>
</body>
The v-repeat directive is deprecated in version 1.0 and replaced with the v-for.
1.0 replaces the old v-repeat directive with v-for. In addition to providing the same functionality and more intuitive scoping, v-for provides up to 100% initial render performance boost when rendering large lists and tables!
http://vuejs.org/2015/10/26/1.0.0-release/#Faster-Initial-Rendering

Guess login with firebase and ember

i try to implement a anonymous login with Ember and Firebase. I have successfully configure my project for use with Firebase and Emberfire, and i can login to my Firebase. But when i try to save user information in a Session initializer, i can't retrieve it to make my controllers aware of the user state.
This is my code :
I have a sidebar in my application.hbs that i want to display if the user is connected.
<div class="container-fluid" id="main">
<div class="row">
{{#if loggedIn}}
<aside class="col-xs-3">
{{outlet sidebar}}
</aside>
<div class="col-xs-9">
{{outlet}}
</div>
{{else}}
<div class="col-xs-12">
{{outlet}}
</div>
{{/if}}
</div>
</div>
Inside of my application.js controller i try to define a computed property :
import Ember from "ember";
var ApplicationController = Ember.ObjectController.extend({
loggedIn :function() {
console.log("Tota", this.session.get('isConnected'));
return this.session.get('isConnected');
}.property(this.session.get('isConnected')),
});
export default ApplicationController;
this.session references an Initializer that is inject inside of controllers and routes :
import Ember from 'ember';
export function initialize(container, application) {
var session = Ember.Object.extend({
authData : [],
user : null,
login : function(authData, user) {
console.log(authData);
console.log(user);
this.set('authData', authData);
this.set('user',user);
},
getUser: function() {
return this.get('user');
},
getAuthData: function() {
return this.get('authData');
},
isConnected : function() {
return (this.get('user') == null) ? false : true;
}.property('user')
});
application.register('session:main', session, { singleton: true });
// Add `session` object to route to check user
application.inject('route', 'session', 'session:main');
// Add `session` object to controller to visualize in templates
application.inject('controller', 'session', 'session:main');
}
export default {
name: 'session',
initialize: initialize
};
And this is my LoginController :
import Ember from "ember";
var LoginController = Ember.ObjectController.extend({
model : {},
ages : function() {
var ages = Ember.A();
for(var i = 18; i <= 99; i++) {
ages.push(i);
}
return ages;
}.property(),
sexs : ['Male', 'Female'],
actions : {
logIn : function() {
var data = this.getProperties("name", "age", "sex");
var that = this;
this.database.authAnonymously(function(error, authData) {
if (error) {
console.log(error);
} else {
var newUser = that.store.createRecord('user', {
name: data['name'],
age: data['age'],
sex:(data['age'] === "Male" ? 0 : 1)
});
newUser.save();
that.session.login(authData, newUser);
console.log("Toto", that.session.get('isConnected'));
that.transitionToRoute('chat');
}
});
}
}
});
export default LoginController;
So in my application.js, if i define loggedIn to be just a property() not property(this.session.get('isConnected'). loggedIn is not refreshed when the user connects to the application. If i tell it to computes with " this.session.get('isConnected') ", Ember tells me that "this.session" is not defined.
How to refresh this value, to tell to my template to display sidebar if my user is connected?
Simple answer
var ApplicationController = Ember.ObjectController.extend({
loggedIn :Em.computed.alias('session.isConnected'),
// or
loggedIn : function(){
return this.get('session.isConnected');
}.property('session.isConnected')
});
Your problem was your dependencies. Either you weren't watching it (property()) or you were crashing because this.session doesn't exist in the scope of the window. And I doubt Ember was really yelling it at you, more of just the javascript engine while it parsing your javascript.
loggedIn :function() {
console.log("Tota", this.session.get('isConnected'));
return this.session.get('isConnected');
}.property(),
// this is resolved while defining the controller, think of its scope
It is resolved like this:
var tmp = this.session.get('isConnected');
var tmp2 = function() {
console.log("Tota", this.session.get('isConnected'));
return this.session.get('isConnected');
}.property(tmp);
var tmp3 = {
loggedIn: tmp2
};
var ApplicationController = Ember.ObjectController.extend(tmp3);

Having trouble updating a scope more than once

I'm using angular with the ionic framework beta 1.
Here's my ng-repeat html:
<a href="{{item.url}}" class="item item-avatar" ng-repeat="item in restocks | reverse" ng-if="!$first">
<img src="https://server/sup-images/mobile/{{item.id}}.jpg">
<h2>{{item.name}}</h2>
<p>{{item.colors}}</p>
</a>
</div>
And here's my controllers.js, which fetches the data for the ng-repeat from a XHR.
angular.module('restocks', ['ionic'])
.service('APIservice', function($http) {
var kAPI = {};
API.Restocks = function() {
return $http({
method: 'GET',
url: 'https://myurl/api/restocks.php'
});
}
return restockAPI;
})
.filter('reverse', function() {
//converts json to JS array and reverses it
return function(input) {
var out = [];
for(i in input){
out.push(input[i]);
}
return out.reverse();
}
})
.controller('itemController', function($scope, APIservice) {
$scope.restocks = [];
$scope.sortorder = 'time';
$scope.doRefresh = function() {
$('#refresh').removeClass('ion-refresh');
$('#refresh').addClass('ion-refreshing');
restockAPIservice.Restocks().success(function (response) {
//Dig into the responde to get the relevant data
$scope.restocks = response;
$('#refresh').removeClass('ion-refreshing');
$('#refresh').addClass('ion-refresh');
});
}
$scope.doRefresh();
});
The data loads fine but I wish to implement a refresh button in my app that reloads the external json and updates the ng-repeat. When I call $scope.doRefresh(); more than once, I get this error in my JS console:
TypeError: Cannot call method 'querySelectorAll' of undefined
at cancelChildAnimations (http://localhost:8000/js/ionic.bundle.js:29151:22)
at Object.leave (http://localhost:8000/js/ionic.bundle.js:28716:11)
at ngRepeatAction (http://localhost:8000/js/ionic.bundle.js:26873:24)
at Object.$watchCollectionAction [as fn] (http://localhost:8000/js/ionic.bundle.js:19197:11)
at Scope.$digest (http://localhost:8000/js/ionic.bundle.js:19300:29)
at Scope.$apply (http://localhost:8000/js/ionic.bundle.js:19553:24)
at done (http://localhost:8000/js/ionic.bundle.js:15311:45)
at completeRequest (http://localhost:8000/js/ionic.bundle.js:15512:7)
at XMLHttpRequest.xhr.onreadystatechange (http://localhost:8000/js/ionic.bundle.js:15455:11) ionic.bundle.js:16905
It looks like it's related to a bug, as per:
https://github.com/driftyco/ionic/issues/727
Which was referenced from:
http://forum.ionicframework.com/t/show-hide-ionic-tab-based-on-angular-variable-cause-error-in-background/1563/9
I'm guessing it's pretty much the same issue.
Maybe try instead using angular.element(document.getElementById('refresh')) for a possible workaround (guessing).

In Backbone Collection, delete a model by link on itself

Im just trying to delete a model from a collection, with a link on itself.
I've attach the event to the "Eliminar button" but it seems Im losing the reference to the model element that contains it... and can't find it.. can you?:
(function ($) {
//Model
Pelicula = Backbone.Model.extend({
name: "nulo",
link: "#",
description:"nulo"
});
//Colection
Peliculas = Backbone.Collection.extend({
initialize: function (models, options) {
this.bind("add", options.view.addPeliculaLi);
this.bind("remove", options.view.delPeliculaLi);
}
});
//View
AppView = Backbone.View.extend({
el: $("body"),
initialize: function () {
this.peliculas = new Peliculas( null, { view: this });
//here I add a couple of models
this.peliculas.add([
{name: "Flying Dutchman", link:"#", description:"xxxxxxxxxxxx"},
{name: "Black Pearl", link: "#", description:"yyyyyyyyyyyyyy"}
])
},
events: {"click #add-movie":"addPelicula", "click .eliminar":"delPelicula"},
addPelicula: function () {
var pelicula_name = $("#movieName").val();
var pelicula_desc = $("#movieDesc").val();
var pelicula_model = new Pelicula({ name: pelicula_name },{ description: pelicula_desc });
this.peliculas.add( pelicula_model );
},
addPeliculaLi: function (model) {
var str= model.get('name').replace(/\s+/g, '');
elId = str.toLowerCase();
$("#movies-list").append("<li id="+ elId +"> " + model.get('name') + " <a class='eliminar' href='#'>Eliminar</a> </li>");
},
delPelicula: function (model) {
this.peliculas.remove();
console.log("now should be triggered the -delPeliculaLi- event bind in the collection")
},
delPeliculaLi: function (model) {
console.log(model.get('name'));
$("#movies-list").remove(elId);
}
});
var appview = new AppView;
})(jQuery);
And my html is:
<div id="addMovie">
<input id="movieName" type="text" value="Movie Name">
<input id="movieDesc" type="text" value="Movie Description">
<button id="add-movie">Add Movie</button>
</div>
<div id="lasMovies">
<ul id="movies-list"></ul>
</div>
There are several things in this code that won't work. Your major problem here is that you don't tell your collection which model to remove. So in your html you have to assign so unique id that later will identify your model.
// set cid as el id its unique in your collection and automatically generated by collection
addPeliculaLi: function (model) {
$("#movies-list").append("<li id="+ model.cid +"> <a href="+ model.get('link')+">" +
model.get('name') + "</a> <a class='eliminar' href='#'>Eliminar</a> </li>"
);
},
// fetch and delete the model by cid, the callback contains the jQuery delete event
delPelicula: function (event) {
var modelId = this.$(event.currentTarget).attr('id');
var model = this.peliculas.getByCid(modelId);
this.peliculas.remove(model);
// now the remove event should fire
},
// remove the li el fetched by id
delPeliculaLi: function (model) {
this.$('#' + model.cid).remove();
}
If there aren't other errors that I have overlooked your code should work now. This is just a quick fix. Maybe you should have a look at the todos example of Backbone to get some patterns how to structure your app.
http://documentcloud.github.com/backbone/examples/todos/index.html

Resources