I'm getting jsonp and putting into an array. When i get near the bottom of the page i'm loading more jsonp and want to add that to the existing array. But instead of adding, its replacing what's already there.
function AppCtrl($scope, Portfolio, $log, $timeout, $ionicSlideBoxDelegate) {
$scope.posts = [];
Portfolio.getPosts($scope);
$scope.refresh = function() {
console.log('Refreshing!');
$timeout( function() {
Portfolio.getPosts($scope);
console.log('Refreshed!');
//stop the ion-refresher from spinning
$scope.$broadcast('scroll.infiniteScrollComplete');
}, 1000);
};
//get jsonp
function Portfolio($http, $log) {
this.getPosts = function($scope) {
$http.jsonp("http://test.uxco.co/json-test.php?callback=JSON_CALLBACK")
.success(function(result) {
$scope.posts = result;
$scope.$broadcast("scroll.infiniteScrollComplete");
});
};
}
Any ideas?
Thanks!
Update:
$scope.posts.push(result);
Seems to work but now the content isn't showing.
<div data-ng-repeat="p in posts">
<div class="img-container">
<img ng-src="{{ p.thumbnail }}">
</div>
<div class="title-container">
<h2>{{ p.id }}</h2>
</div>
</div>
function Portfolio($http, $log) {
this.getPosts = function($scope) {
$http.jsonp("http://test.uxco.co/json-test.php?callback=JSON_CALLBACK")
.success(function(result) {
$scope.posts.push(result);
$scope.$broadcast("scroll.infiniteScrollComplete");
});
};
}
Related
I have a parent controller with some children controllers, and I want them all to share the same data that I retrieve from an Api service.
Controllers:
var app = angular.module('mymodule',[]);
app.controller('main', ['$scope', 'Api', function($scope, Api) {
var getList1 = Api.getList1()
.then(function(resp) {
$scope.list1 = resp.data;
});
var getList2 = Api.getList2()
.then(function(resp) {
$scope.list2 = resp.data;
});
}]);
app.controller('child1', ['$scope', function($scope) {
$scope.list1 = ?
$scope.list2 = ?
}]);
app.controller('child2', ['$scope', function($scope) {
$scope.list1 = ?
}]);
View:
<div ng-controller="main">
<ul>
<li ng-repeat="list in list1">
{{list.item}}
</li>
</ul>
<div ng-controller="child1">
<ul>
<li ng-repeat="list in list1">
{{list.item}}
</li>
</ul>
<ul>
<li ng-repeat="list in list2">
{{list.item}}
</li>
</ul>
</div>
<div ng-controller="child1">
<ul>
<li ng-repeat="list in list1">
{{list.item}}
</li>
</ul>
</div>
</div>
I tried to use this solution with Angular’s events mechanism ($on, $emit).
The problem was that I had to figure out which child controller is active and send the data when the promise has resolved. It ends with ugly spaghetti code...
Well, the best way is to use a service to have your API handling atomar placed inside your application. This fiddle shows you how you could achieve what you try to. By using AngularJS services you will be able to share the same data, objects and functions between controllers and let them interact with eachother. This is undepending on the amount of your controllers inside your application.
The following example is a full working API service with real HTTP-Requests and a real AngularJS service handling. It will help you by implement such logic inside your application. Please dont forget to check out the fiddle demo.
View
<div ng-controller="MyCtrl">
<h1>
MyCtrl
</h1>
<button ng-click="clearData()">
Clear data by using MyCtrl
</button>
<div ng-repeat="user in users">
<p>
Username: {{ user.name }}
</p>
</div>
</div>
<br /><br />
<div ng-controller="MyOtherCtrl">
<h1>
MyOtherController
</h1>
<button ng-click="clearData()">
Clear data by using MyOtherController
</button>
<div ng-repeat="user in users">
<p>
Username: {{ user.name }}
</p>
</div>
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);;
myApp.controller('MyCtrl', function ($scope, apiService) {
$scope.users = apiService.getResponseData();
$scope.$watch(function () { return apiService.getResponseData()}, function (newValue, oldValue) {
$scope.users = newValue
});
$scope.clearData = function () {
apiService.reset();
}
});
myApp.controller('MyOtherCtrl', function ($scope, apiService) {
apiService.loadData();
$scope.$watch(function () { return apiService.getResponseData()}, function (newValue, oldValue) {
$scope.users = newValue
});
$scope.clearData = function () {
apiService.reset();
}
})
myApp.service('apiService', function ($http) {
var responseData = null;
return {
loadData: function () {
return $http({
url: 'https://jsonplaceholder.typicode.com/users',
method: 'GET'
}).then(function (response) {
responseData = response.data
});
},
getResponseData: function () {
return responseData
},
reset: function () {
responseData = null;
}
}
});
As your data is in the scope of the parent controller, you can access it in children controllers with $scope.$parent:
app.controller('child1', ['$scope', function($scope) {
$scope.list1 = $scope.$parent.list1;
$scope.list2 = $scope.$parent.list2;
}]);
Write your children as directives, and then you can inject data on the scope.
yourModule.directive('child1', function() {
return {
scope: {list1:'=',
controller: function (scope) {
//not sure you even need a controller, but it might look like this
scope.doSomething = function() {
//access scope.list1 here
}
},
template: '<ul><li ng-repeat="list in list1">{{list.item}}<li><ul>'
}
}
Usage:
<child1 list1="list1"></child1>
I already have seem other topics with this kind of issue, but no one could help me... So here is my issue:
I have a navbar with a button for search, this buttons makes and get request from a webservice and returns a json object which must be apply to fill an table list. The problem is, my button and my table are in separated controllers, and it does work like I expected.
var app = angular.module('clientRest', []).controller('lista', ['$scope', 'loadLista', function($scope, loadLista) {
$scope.contatos = loadLista.getContatos();
}]).controller('pesquisa', ['$scope', '$http', 'loadLista', function($scope, $http, loadLista) {
$scope.listar = function() {
$http.get("http://localhost/wsRest/index.php/contato").success(function(response) {
loadLista.setContatos(response);
});
};
}]).service('loadLista', function() {
var contatos = [];
return {
getContatos: function() {
return contatos;
},
setContatos: function(c) {
contatos = c;
}
};
});
My code...
When I call listar() from pesquisa controller I need to send received data to $scope.contatos from lista controller to make my ng-repeat work, everything with a single click.
How can I do it?
Thanks everyone
Better to use a service to share data between two controllers / modules as this might be the best approach. You can refer the code segment given below to understand the concept.
angular.module('app.A', [])
.service('ServiceA', function() {
this.getValue = function() {
return this.myValue;
};
this.setValue = function(newValue) {
this.myValue = newValue;
}
});
angular.module('app.B', ['app.A'])
.service('ServiceB', function(ServiceA) {
this.getValue = function() {
return ServiceA.getValue();
};
this.setValue = function() {
ServiceA.setValue('New value');
}
});
In order to trigger the data receipt event, you may use
Broadcast / emit messages - with #broadcast / #emit
An angular promise with a call back
Controller initiation function to reload the previously read information from a service
.controller('MyController', function($scope, ServiceA) {
$scope.init = function() {
$scope.myValue = ServiceA.getValue();
};
// Call the function to initialize during Controller instantiation
$scope.init();
});
Use $rootScope.$emit to emit a change event when setting the variable and use $on to get the value in the lista controller. I used customListAr here just to demostrate a button click. Does this help?
var app = angular.module('clientRest', [])
.controller('lista', ['$scope', 'loadLista', '$rootScope',
function($scope, loadLista, $rootScope) {
console.log(loadLista);
$scope.contatos = loadLista.getContatos();
$rootScope.$on('change', function() {
$scope.contatos = loadLista.getContatos();
});
}
])
.controller('pesquisa', ['$scope', '$http', 'loadLista',
function($scope, $http, loadLista) {
$scope.listar = function() {
$http.get("http://localhost/wsRest/index.php/contato").success(function(response) {
loadLista.setContatos(response);
});
};
$scope.customListAr = function() {
loadLista.setContatos(["item 1" , "item 2", "item 3"]);
}
}
])
.service('loadLista', ['$rootScope',
function($rootScope) {
var contatos = [];
return {
getContatos: function() {
return contatos;
},
setContatos: function(c) {
contatos = c;
$rootScope.$emit('change');
}
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="clientRest">
<div ng-controller="lista">
<ul>
<li ng-repeat="a in contatos">{{a}}</li>
</ul>
</div>
<div ng-controller="pesquisa">
<button ng-click="customListAr()">Click Me</button>
</div>
</div>
Your problem is that when you do $scope.contatos = loadLista.getContatos(); you are setting a static value, and angular is unable to effectively create a watcher for that object because your setContatos method is creating a new object each time. To get around this, have the controller's scope hold a reference to the parent object and then it will automatically have a watcher on that object.
var app = angular.module('clientRest', [])
.controller('lista', ['$scope', 'loadLista', function($scope, loadLista) {
$scope.contatos = loadLista.contatos;
}])
.controller('pesquisa', ['$scope', '$http', 'loadLista', function($scope, $http, loadLista) {
$scope.listar = function() {
$http.get("http://localhost/wsRest/index.php/contato"
).success(function (response) {
loadLista.contatos.data = response;
});
};
}])
.service('loadLista', function() {
var lista = {
contatos: {},
};
return lista;
});
// view:
<ul>
<li ng-repeat="contato in contatos.data">
{{ contato }}
</li>
</ul>
I try to build new APP with ionic framework and Angularjs.
Now my problem is i cannot show the result from controller to view. I try open console.log(allposts); in my browser ans we show the result good.
But in view its not show any thing
allpost.html
<dive class="item itemfull" ng-repeat="post in allpost">
<div class="item item-body">
<div>{{ post.title }}
<div class="title-news"><div class="title" ng-bind-html="post.content"></div></div>
</div>
</div>
</div>
And the controller
myApp.controller('allpost', function($scope , $http , $stateParams , Allposts) {
var id = $stateParams.id;
$scope.post = Allposts.GetAllposts(id);
});
myApp.factory('Allposts',['$http', '$q',function($http,$q){
var allposts = [];
var pages = null;
return {
GetAllposts: function (id) {
return $http.get("http://kotshgfx.info/azkarserv/?json=get_category_posts&id="+id+"&status=publish",{params: null}).then(function (response) {
items = response.data.posts;
allposts = items;
console.log(allposts);
return items;
$ionicLoading.hide();
});
}
}
}]);
Where is error ?
try to change the code like this in controller and factory in js files
.controller('allpost', function ($scope, $http, $stateParams, Allposts) {
var id = $stateParams.id;
Allposts.GetAllposts(id).then(
function (response) {
$scope.allPosts = response.data.posts;
});
})
.factory('Allposts', ['$http', '$q', function ($http, $q) {
return {
GetAllposts: function (id) {
return $http.get("http://kotshgfx.info/azkarserv/?json=get_category_posts&id=" +
id + "&status=publish");
}
}
}]);
the html file
<div class="item itemfull" ng-repeat="post in allPosts">
<div class="item item-body">
<div>{{ post.title }}
<div class="title-news">
<div class="title" ng-bind-html="post.content"></div>
</div>
</div>
</div>
</div>
It works for my test
I am having trouble using the Angular filter in my app.
I have something like
app.controller('test', function($scope, $filter){
myService.get('api/v1/products/?id=1').success(function(data) {
$scope.products = data;
$filter('testFilter', function() {
return function(products, item) {
//codes...
}
})
})
}
html
<div ng-repeat="product in products | testFilter:5 "> {{product.title}} </div>
However, I am getting testFilterProvider unknown error. Can someone help me out on this one? Thanks a lot!
To create a filter, you need to call filter() on the module...
app.filter('testFilter', function() {
return function(products, item) {
//codes...
};
});
And if you want use that filter in your controller, you can call the $filter service to retrieve it...
app.controller('test', function($scope, $filter){
myService.get('api/v1/products/?id=1').success(function(data) {
$scope.products = data;
var filteredProducts = $filter('testFilter')($scope.products, 5);
});
}
I'm going to try my best to explain this problem. I am also new to Angular so bear with me.
I have two routes that use the same template...
ExampleApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/logbook/following', {
templateUrl: 'views/surf.html',
})
.when('/logbook/following/:surf_id', {
templateUrl: 'views/surf.html',
})
}]);
with two controllers
AppControllers.controller('LogbookController', function($scope, $http, $location, $routeParams) {
$scope.surfs = null;
// Get feed
$http.get(RestURL + 'feeds?filter=following' ).success(function(data) {
if(typeof $routeParams.surf_id == "undefined") {
if(data.length > 0) {
$location.path('/logbook/following/' + data[0].id);
$scope.loadSurfDetail(data[0].id);
}
}
$scope.surfs = data;
});
});
AppControllers.controller('SurfController', function($scope, $http, $location, $routeParams) {
$scope.loading = false;
// Load surf
$scope.loadSurfDetail = function(surfID) {
$scope.loading = true;
$scope.selectedSurf = null;
// Get surf
$http.get(RestURL + 'surfs/' + surfID).success(function(data) {
$scope.selectedSurf = data;
$scope.loading = false;
});
};
if($routeParams.surf_id) {
$scope.loadSurfDetail($routeParams.surf_id);
}
});
using this template file:
<div class="row">
<div class="logbook col-md-3" ng-controller="LogbookController">
<h1>Logbook</h1>
<ol class="surfs-feed">
<li data-id="{{feedSurf.id}}" ng-repeat="feedSurf in surfs" class="surf">
<a href="#/logbook/following/{{feedSurf.id}}">
<strong>{{feedSurf.user.first_name}} {{feedSurf.user.last_name}}</strong>
</a>
</li>
</ol>
</div>
<div class="surf col-md-9" ng-controller="SurfController">
<p class="alert alert-info" ng-show="loading">
Loading...
</p>
<div class="surf-detail" ng-show="selectedSurf">
<pre>
{{selectedSurf | json}}
</pre>
</div>
</div>
</div>
My issue is that when I load a deep link URL, ie. /logbook/following/:surf_id it will use the same template as /logbook/following (adove) and that will cause the logbook feed to be regenerated each time you load up a new surf. So each time you load the surf, the logbook "blinks" and regenerates.
I would like to know how people have tackled this problem without refreshing the feed of surfs and just updating the detail panel on the right hand side...
Thanks!
In your app config, inject $locationProvider and set its html5Mode parameter to true. Then, route changes will not cause the page to refresh.
ExampleApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/logbook/following', {
templateUrl: 'views/surf.html',
})
.when('/logbook/following/:surf_id', {
templateUrl: 'views/surf.html',
})
$locationProvider.html5Mode(true);
}]);