angular js model doesn't bind - javascript

I am using AngularJS and I don't manage to bind properly models that need time to load. I have this service called ListService:
angular.module('3pix').factory('ListService', ['$q', '$timeout', 'underscore', 'Item', 'ItemResource',
function ($q, $timeout, _, Item, ItemResource) {
var List = function () {
};
_.extend(List.prototype, {
_addItem: function(item) {
this.items || (this.items = []);
this.items.push(item);
},
loadItems: function() {
var scope = this;
var deferred = $q.defer();
ItemResource.get_items({id: 39}, function(itemsData) {
itemsData.forEach(function(itemData) {
scope._addItem(new Item(itemData));
});
deferred.resolve(scope.items);
});
return deferred.promise;
}
});
return List;
}]);
My real ListService is far more complicated than this but I copied only the relevant parts so I can ask my question clearly.
My controller called ListController and it gets a 'list' from the router using 'resolve' option:
angular.module('3pix').controller('ListController', ['$scope', 'jquery', 'list',
function ($scope, $, list) {
$scope.list = list; //<-------- Here I got the list, I get it fine from the router
list.loadItems(); //<------- Here I load the list's items
}]);
In my view I have:
<div class="item-wrapper"
ng-repeat="item in list.items">
{{item}}
</div>
My problem is that after the items are loaded in the controller, the view doesn't displays the items and keeps drawing nothing. I tried to wrap the loadItems's success method in $timeout and $rootScope.$apply but it doesn't help. Any idea how to solve it?
UPDATE
I followed the advice of #Chandermani and I did in my controller:
list.loadItems().then(function() {
$scope.items = list.items;
});
The items are loaded in the view, but still, sometimes, when I update list.items using _addItem() method, nothing happen and the view doesn't show the new items. I tried to wrap _addItem() with $timeout as follows but it didn't helped either:
_addItem: function(item) {
$timeout(function() {
this.items || (this.items = []);
this.items.push(item);
});
}

I think the problem is that you are assigning the scope list to the service instance instead of the method result.
Change it to
angular.module('3pix').controller('ListController', ['$scope', 'jquery', 'list',
function ($scope, $, list) {
$scope.list = list.loadItems()
}]);
Also can you try this in html
ng-repeat="item in list"

Related

Using AngularJS with a factory and a Controller

I'm trying to do the following:
When a user accesses "localhost/people/:id", the information about the respective person is taken from a MongoDB and displayed via Angular.
I have my api, which works perfectly fine, I've double-checked.
I'm using the latest AngularJS (1.4.9) and the new Router (angular-new-router or ngNewRouter).
I have an Angular module:
var personModule = angular.module('app.personDetailed', []);
a factory:
personModule.factory('personService', ['$http', function($http) {
return {
get : function(id) {
return $http.get('/api/people/' + id);
}
}
}]);
and a controller:
personModule.controller('PersonDetailedController', ['$routeParams', '$scope', 'personService', PersonDetailedController]);
function PersonDetailedController($routeParams, $scope, personService) {
var id = $routeParams.id;
personService.get(id).then(function(res) {
$scope.item = res.data;
});
}
This all should be displayed in this view:
<div data-ng-controller="PersonDetailedController">
<h2>{{ item }}</h2>
</div>
(yes, I'm not bothering trying to parse json yet).
The problem is, I am unable to use both $scope and $routeParams at the same time. I can only have one or the other. If I use both, the $scope works fine, but the $routeParams is empty.
Here's the main controller, just in case:
var appModule = angular.module('app', ['app.main', 'app.personDetailed', 'ngNewRouter', 'ngResource']);
appModule.controller('AppController', ['$router', AppController]);
function AppController($router) {
$router.config([
{ path: '/', component: 'main'}
{ path: '/people/:id', component: 'personDetailed'}
]);
}
Seems the new router does away with $scope and binds to the controller instance in the template instead.
Looks like you should use this instead
personModule.controller('PersonDetailedController', ['$routeParams', 'personService', PersonDetailedController]);
function PersonDetailedController($routeParams, personService) {
var personDetailed = this,
id = $routeParams.id;
personService.get(id).then(function(res) {
personDetailed.item = res.data;
});
}
and your view (do not use ng-controller)
<h2>{{ personDetailed.item }}</h2>

What's the most common reason for ModalInstanceCtrl to give this error?

I am trying to hook up an Angular Bootstrap modal (pop-up) but it's giving me either "templateUrl" not found error, or this error: Error: [ng:areq] http://errors.angularjs.org/1.3.15/ng/areq?p0=ModalInstanceCtrl&p1=not%20a%20function%2C%20got%20undefined
I just want some theoretical suggestions on why that would be the case. I have tried a lot of things: it's all properly hooked up, all the spelling matches, etc, etc.
$modal is being used in the controller with other functions as well, so it's all being injected.
Angular Documents provide a suggestion that when you get this error it is possible that you have a controller being injected into another controller. Which is exactly what was happening with my attempt to add a modal as their box solution:
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $modal, $log) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.animationsEnabled = true;
$scope.open = function (size) {
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.toggleAnimation = function () {
$scope.animationsEnabled = !$scope.animationsEnabled;
};
});
controller: 'ModalInstanceCtrl' MUST BE removed from your modal function if you're adding it to an existing controller, otherwise it will all go to ... you know where.
Can be as simple as the controller not existing on your module.
I forgot to add the code for the modal controller :( when I first tried it in my project
This controller is about 3 controllers deep in my project (make sure your using "controller AS cntlr" style) so embedding wasn't a problem for me.
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$uibModalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
});

Sharing data between controllers, AngularJS

I'm facing the following situation in my Angular application and I would like to have some advices here.
I have a page where I show some products, this page is managed by a controller called 'ProductsController'. This controller has a method called 'showProductDetails' which is called once the user clicks on a specific product, and the goal of this method is just to retrieve the details of the product and to display these details in a modal panel.
Nothing really special until here. The problem is that because of modularity I would like to attach a different controller to the modal panel, and to manage all the logic of this modal panel in the new controller, in this case 'ProductDetailController'. The problem is that I retrieve the data of the product before opening the modal panel, but as I retrieve this data in the scope of the first controller, from the second controller I cannot access to the product that I have previously retrieved. I've been told that to share data between controllers in angularJs is done through services, but I don't see how a stateless service can help me here.
Here is my code to understand better the situation:
The first controller:
app.controller('ProductsController', ['$scope','productsFactory','commonFactory','productsFactoryHelper','$filter','$modal',function ($scope,productsFactory,commonFactory,productsFactoryHelper,$filter,$modal)
{
$scope.showProductDetails = function (size,product) {
$scope.showLoader('Loading the details of the product. Please wait...');
productsFactoryHelper.Product.query({id:product.id},function(response)
{
$scope.selectedProduct=response;
$scope.hideLoader();
var modalInstance = $modal.open({
templateUrl: 'productDetail.html',
controller: 'ProductDetailController',
size: size
});
},function(error)
{
commonFactory.Pop('error','This product is not available at this moment. Please try again later. If the problem persists contact a system administrator');
$scope.hideLoader();
});
};
_init();
}]);
And the second controller:
app.controller('ProductDetailController',['$scope','$modalInstance', function ($scope, $modalInstance) {
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
So basically the question is how can access from the 'ProductDetailController' to the object 'selectedProduct' which is in the scope of the 'ProductsController'.
Thank you for your help.
Use resolve of the $modal to send your data to the new controller like below.
app.controller('ProductsController', ['$scope','productsFactory','commonFactory','productsFactoryHelper','$filter','$modal',function ($scope,productsFactory,commonFactory,productsFactoryHelper,$filter,$modal)
{
$scope.showProductDetails = function (size,product) {
$scope.showLoader('Loading the details of the product. Please wait...');
productsFactoryHelper.Product.query({id:product.id},function(response)
{
$scope.selectedProduct=response;
$scope.hideLoader();
var modalInstance = $modal.open({
templateUrl: 'productDetail.html',
controller: 'ProductDetailController',
size: size,
resolve:{
"selectedProduct":response
}
});
},function(error)
{
commonFactory.Pop('error','This product is not available at this moment. Please try again later. If the problem persists contact a system administrator');
$scope.hideLoader();
});
};
_init();
}]);
I dont know about the producfactory helper product query has a promise if it has a promise you can use like this..
$scope.showProductDetails = function (size,product) {
$scope.showLoader('Loading the details of the product. Please wait...');
var modalInstance = $modal.open({
templateUrl: 'productDetail.html',
controller: 'ProductDetailController',
size: size,
resolve:{
"selectedProduct":productsFactoryHelper.Product.query({id:product.id})
}
});
};
And in the ProductDetailController you can inject this selectedProduct like below
app.controller('ProductDetailController',['$scope','$modalInstance','selectedProduct ' function ($scope, $modalInstance,selectedProduct ) {
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
This can indeed be done through services, since they are stateless and keep their data once instantiated.
function productService($http) {
this.products = [];
this.loadProducts() {
$http.get('/url/to/your/product/api').then(function(err, data) {
this.products = data.products;
});
};
this.getProducts = function() {
return this.products;
}
}
angular
.module('yourModule')
.service('productService', productService);
You can then just inject productService in both controllers, load the products using productService.loadProducts(), and get them using productService.getProducts().
This is just an example. Services can be used to share any kind of data.
Services are indeed the answer for you, or you can use pure eventing if you do not need to access the data more then once.
Pure Eventing
app.controller('parentCtrl', function($scope) {
// Do something
// Action completed
#scope.$emit('someactionComplete', data);
});
app.controller('childCtrl', function($scope) {
$scope.$on('someactionComplete', function(data) {
// Process data
});
});
Using a service. The advantage of using a service is that the data is persisted.
app.controller('parentCtrl', function($scope, MyService) {
// Do something
// Action completed
MyService.setData(data);
#scope.$emit('someactionComplete');
});
app.controller('childCtrl', function($scope) {
$scope.$on('someactionComplete', function() {
MyService.getData(data);
});
});
You could further enhance this were the service loaded the data and returns a promise in the getter.

How to pass data to different controller in my case?

I am trying to create factory for the restful services.
I need to make service calls. First call's data will be used to get the second calls data.
My problem is I don't know how to transfer data from one controller to another controller.
Is there a better way to do my codes?
Here are my codes...
var app = angular.module('myApp', []);
//getting init data via service
app.factory('myService', function($http) {
var myService = {
async: function() {
var promise = $http.get('test/test.json').then(function (response) {
return response.data;
});
return promise;
}
};
return myService;
});
//retrieve data
app.controller('testCtrl', function(myService, $scope, $http) {
myService.async().then(function(data) {
$scope.data = data
//using retrieve data to get another piece of data
vay first = data[0].employee[0];
})
$http({
url: "test?" + first +'.json',
method: "GET",
}).success(function(secondData) {
$scope.secondData=secondData //How do I pass data to my secondCtrl?
})
})
app.controller('secondCtrl', function($scope) {
// I need to be able to get the secondData from testCtrl.
console.log($scope.secondData)
})
Thanks for the help!
Why don't you store the data as an object in the service itself, then both controllers depend on the service and have access to the data. Like this:
app.factory('myService', function($http) {
var that = this;
var myService = function($http) {
this.set = function(url) {
var promise = $http.get(url).then(function (response) {
that.data = promise.data;
});
return promise;
}
};
return new myService($http);
});
Then your controller sets and gets the data in the way
app.controller('testCtrl', function(myService, $scope, $http) {
myService.set('someurl').then(function() {
$scope.data = myservice.data;
//using retrieve data to get another piece of data
vay first = data[0].employee[0];
myservice.set('someOtherUrl?data='+first);
})
app.controller('secondCtrl', function($scope, myservice) {
//the data object on the myservice function has been changed on the first controller and we can reasonably expect the data we need. If these 2 controllers coexist in the same space and time we can wrap this in a $watch service
console.log(myservice.data)
});
$watch service example
app.controller('secondCtrl', function($scope, $watch, myservice) {
$watch('myservice.data', function(newval, oldval) {
console.log(newval);
}, true)
//I will only log the newvalue of myservice.data when the data has changed. the last true argument is a neccesity so that angular will compare the values within the object
});
You could either extend 'myService' to contain the response data, using it in both controllers, or you could create another service for sharing data between them.
Both solutions would look similar, but here is what the second option (new service) might look like:
Factory
.factory('SharedService', function(){
var shared = {
data: ''
}
return shared;
})
This factory could act as just a place to store some data. In fact, if all you'd like to do is share data, you could just use a value provider. But a factory you could later extend with a more complex data structure and methods.
In your controllers, just inject the service and, optionally, set it to a scope variable:
Controller 1
.controller('FirstController', function($scope, SharedService){
$scope.shared = SharedService;
$scope.shared.data = 'foo';
})
$scope.shared now references the service object. If you were to do the same in the other controller, they could both read/write to that same object:
Controller 2
.controller('SecondController', function($scope, SharedService){
$scope.shared = SharedService;
console.log($scope.shared.data); // 'foo' if called after first ctrl set it
})
Demo

Best practice to set up a service or factory for $http contacting to REST API in AngularJS

I've created $http and REST API interface in AnguarJS service as a function that gets injected into different controllers like this:
// Global service to share between states
.service("appSharedService", ['$http', function($http) {
// Method: Returns list of all cities.
this.restCitiesGet = function() {
return $http.get('http://example/nkhorasaniec7/api/v0/city');
};
// Method:
this.citiesGet = function() {
this.restCitiesGet().success(function (data) {
console.log(data);
return data;
})
};
}])
console.log(data); returns the right json output when I call citiesGet() .
// Main controller that prints list of cities.
.controller('CityList', ['$scope', function($scope, appSharedService) {
$scope.cities = appSharedService.citiesGet();
console.log($scope.cities);
}]);
This is my controller injecting my service. console.log($scope.cities); here returns undefined.
$scope.cities value doesn't get changed after route calls this controller.
Is there something wrong with my setup?
Something interesting is that after I change route and come back to this controller again, this time $scope.cities have my REST data and everything's fine.
I think there's something wrong with timing or asynchronous functionality problem here that I'm not aware of.
EDIT:
I could have had $http in my controller and this works all well:
.controller('CityList', ['$scope', '$http', function($scope, $http, appSharedService) {
$http.get('http://localhost/nkhorasaniec7/api/v0/city').success(function (data) {
$scope.cities = data;
});
}]);
But I want to implement helper functions for this.
I would say that the common approach would be to return the promise directly to the controller, much like you have mentioned above by directly using the http request.
// Global service to share between states
.service("appSharedService", ['$http', function($http) {
// Method: Returning the promise
this.citiesGet = function() {
return $http.get('http://example/nkhorasaniec7/api/v0/city');
};
}])
Controller:
.controller('CityList', ['$scope', '$http', function($scope, $http, appSharedService) {
appSharedService.citiesGet().success(function (data) {
$scope.cities = data;
});
}]);
I think you are right about the timing issue. From what I understand, you are getting a promise, that at the moment you do console.log($scope.cities) is not yet resolved.
If you use $scope.cities inside your page, you should see the results as soon as they are loaded. Another option would be to use the promise then function if you really want to log.
$scope.cities = appSharedService.citiesGet().then(function(data) {
console.log(data);
return data;
};
Answering my own question:
I'm trying to make this happen in my a controller defined in my view using ng-controller, not a controller linked to a router (otherwise you could use resolve property like this Delaying AngularJS route change until model loaded to prevent flicker).
And I want to use REST using $http as a factory/service helper function for a cleaner code.
// Global service to share between states
.service("appSharedService", ['$http', '$q', function($http, $q) {
this.citiesGet = function() {
var deferred = $q.defer();
$http({method: 'GET', url: 'http://localhost/nkhorasaniec7/api/v0/city'}).success(function(data) {
deferred.resolve(data);
}).error(function(data, status) {
deferred.reject(data);
});
return deferred.promise;
};
}])
I used angular $q promise here.
// Our main controller that prints list of cities.
.controller('CityList', ['$scope', 'appSharedService', function($scope, appSharedService) {
var promise = appSharedService.citiesGet();
promise.then(
function(data){$scope.cities = data;}
,function(reason){alert('Failed: ' + reason);}
);
}])
And used then function to use that promise.
And now it always updates $scope.cities in any situation that template loads (not just in ng-view)
You can use $q service
.service("appSharedService", ['$http', '$q', function($http, $q) {
// Method: Returns list of all cities.
this.restCitiesGet = function() {
var deffered = $q.defer();
$http.get('http://example/nkhorasaniec7/api/v0/city').then(
//success
function(response){
deffered.resolve(response.data);},
//error
deffered.reject();
);
return deffered
};
and after that you can use promise in you controller
.controller('CityList', ['$scope', function($scope, appSharedService) {
$scope.cities = []
appSharedService.citiesGet().then(
//success
function(result){
angular.copy(result, $scope.cities)
console.log($scope.cities);
},
//error
function(){
console.log("load error");
});
}]);

Categories