Angular controller get model asynchronously - angularjs

I have a controller that starts like this (simplified for this question):
angular.module('myApp.controllers')
.controller('MyController', ['$scope', '$routeParams', 'MyService',
function ($scope, $routeParams, MyService) {
MyService.fetchWithId($routeParams.id).then(function(model) {
$scope.model = model;
});
Which is fine, but then in many places throughout the controller, I have functions that are referred to in the view that refer to the model ...
$scope.someFunctionMyViewNeeds = function() {
return $scope.model.someModelAttribute;
};
Since these often run before the fetch completes, I end up with errors like "cannot read property of undefined" when the view tries to see someModelAttribute.
So far, I've tried three things:
// before the fetch
$scope.model = new Model();
...but I really don't want a new model, and in some cases, cannot complete initialization out of the blue without other dependences.
Another idea is to litter the code with defense against the unready model, like:
return ($scope.model)? $scope.model.someModelAttribute : undefined;
... but that's a lot of defense all over the code for a condition that only exists while the fetch completes.
My third idea has been to "resolve" the model in the route provider, but I don't know how to do that and get at the $routeParams where parameter to fetch the model is kept.
Have I missed a better idea?

Try this if you want to use resolve.
var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/things/:id', {
controller: 'ThingsShowController',
resolve: {
model: function ($routeParams, MyService) {
return MyService.fetchWithId(+$routeParams.id);
}
},
template: '<a ng-href="#/things/{{model.id}}/edit">Edit</a>'
});
$routeProvider.when('/things/:id/edit', {
controller: 'ThingsEditController',
resolve: {
model: function ($routeParams, MyService) {
return MyService.fetchWithId(+$routeParams.id);
}
},
template: '<a ng-href="#/things/{{model.id}}">Cancel</a>'
});
});
// Just inject the resolved model into your controllers
app.controller('ThingsShowController', function ($scope, model) {
$scope.model = model;
});
app.controller('ThingsEditController', function ($scope, model) {
$scope.model = model;
});
// The rest is probably irrelevant
app.factory('Model', function () {
function Model(attributes) {
angular.extend(this, attributes);
}
return Model;
});
app.service('MyService', function ($q, Model) {
this.fetchWithId = function (id) {
var deferred = $q.defer();
deferred.resolve(new Model({ id: id }));
return deferred.promise;
};
});
// Just to default where we are
app.run(function ($location) {
$location.path('/things/123');
});
app.run(function ($rootScope, $location) {
$rootScope.$location = $location;
});
// Because $routeParams does not work inside the SO iframe
app.service('$routeParams', function () {this.id = 123;});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.9/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.9/angular-route.min.js"></script>
<div ng-app="app">
<div>Route: {{$location.path()}}</div>
<div ng-view=""></div>
</div>

Related

how to call the method of controller in routeProvider resolve function

I wanna update the data and then show the view bound with this controller, the code is as follow
angular.module('myApp.student', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/student', {
templateUrl: 'student/student.html',
css: 'student/assets/student.css',
controller: 'studentCtrl',
demand: 'admin'
});
}])
.controller('studentCtrl', ['$scope', 'baseDataUrl', '$http', function($scope, baseDataUrl, $http) {
$scope.update = function() {
$http.get(baseDataUrl + '/student/list').then(function(res) {
$scope.students = res.data;
});
};
$scope.orderProp = "name";
$scope.update();
}]);
how can i do this as there is no way to inject the controller to the config as I know
You could write something like...
angular.module('myApp.student', ['ngRoute'])
.config('routeConfig', function($routeProvider) {
$routeProvider.when('/student', {
templateUrl: 'student/student.html',
css: 'student/assets/student.css',
controller: 'studentCtrl',
demand: 'admin',
resolve: { students : function ($http, baseDataUrl) {
return $http.get(baseDataUrl + '/student/list').then(function (res) {
return res.data;
});
}
}
});
})
.controller('studentCtrl', ['$scope', function($scope, students) {
$scope.students = students;
$scope.orderProp = "name";
}]);
Note that baseDataUrl must either be a constant, or a provider that calls a function to get the required data (in which case, it should be something like baseDataUrl.getUrl()).
With this, it is ensured that every time the /student route is accessed, the scope variable $scope.students contains updated data.

Angular [$injector:unpr] Unknown provider with customize directive

I have a little issue by using a customize directive within the template field of UI-Bootstrap modal directive.
My aim is send data to modal via resolve attribute and re-use these resolved parameters inside the controller of my own directive.
var app = angular.module('app', ['ui.bootstrap']);
app.controller('MyCtrl', ['$scope', '$modal', function($scope, $modal) {
$scope.openModal = function () {
var popup = $modal.open({
template: '<my-modal></my-modal>',
resolve : {
mydata : function() {
return 42;
}
}
});
};
}]);
app.controller('ModalController', ['$scope', 'mydata', function($scope, mydata) {
//The error is in this directive controller
$scope.mydata = mydata;
}]);
app.directive('myModal', function() {
return {
restrict: 'E',
templateUrl : 'mymodal.html',
controller : 'ModalController',
replace: true
};
});
Maybe I proceed in the wrong way.
Any suggest to make this code functionnal ?
http://plnkr.co/edit/RND2Jju79aOFlfQGnGN8?p=preview
The resolve parameters are only injected to the controller defined in the $modal.open config parameters, but you want to inject it to the directive controller. That will not work. Imagine you would use the myModal directive somewhere else, there wouldn't be a myData object that could be used.
But i don't realy see, what you need the directive for. You could go much easier this way:
app.controller('MyCtrl', ['$scope', '$modal',
function($scope, $modal) {
$scope.openModal = function() {
var popup = $modal.open({
templateUrl: 'mymodal.html',
controller: 'ModalController',
resolve: {
mydata: function() {
return 42;
}
}
});
};
}
]);
// Here the mydata of your resolves will be injected!
app.controller('ModalController', ['$scope', 'mydata',
function($scope, mydata) {
$scope.mydata = mydata
}
]);
Plunker: http://plnkr.co/edit/bIhiwRjkUFb4oUy9Wn8w?p=preview
you need to provide an Object "mydata". Ensure, that you have a correct implemented factory which provides your myData Object. If you had done that, you can "inject" your myData Object where ever you want to.
yourApp.MyDataFactory = function () {
var myData = {i: "am", an: "object"};
return myData;
}
this would provide an "myData" Object
I'm not sure what you are trying to accomplish with the directive, but if you are trying to provide a generic way to invoke the $model, that you can then use from many places in your app, you may be better off to wrap $model with a service. Than you can then call from other places in your app.
I forked and modified your plunkr to work this way: http://plnkr.co/edit/0CShbYNNWNC9SiuLDVw3?p=preview
app.controller('MyCtrl', ['$scope', 'modalSvc', function($scope, modalSvc) {
var mydata = {
value1: 42
};
$scope.openModal = function () {
modalSvc.open(mydata);
};
}]);
app.factory('modalSvc', ['$modal', function ($modal) {
var open = function (mydata) {
var modalInstance,
modalConfig = {
controller: 'ModalController',
resolve: {
mydata: function () {
return mydata;
}
},
templateUrl: 'mymodal.html'
};
modalInstance = $modal.open(modalConfig);
return modalInstance;
};
return {
open: open
};
}]);
Also, I changed mydata to be an object, rather than '42', as I am sure you will have other data to pass in. the markup was updated accouringly:
<div class="modal-body">
BODY {{mydata.value1}}
</div>
Doing it this way, the resolve property works, and you can get your data.
As for the other answers mentioning you must define mydata, the resolve property passed into $model does this for you, so it can be injected into the modal's controller (ModalController), like you have done.

Parent view does not get updated

I am using angular with ngDialog. I have in my view a list of users with an edit button which opens the user details in a ngDialog. Now when i save the data in my ngDialog I would like the list of users to be updated.
I thought to use a observer pattern for this. However the handler doesn't fire.
Here is my code:
User Controller
angular.module('myApp')
.controller('UserController', function($scope, User){
//this method gets fired when the dialog is saved
$scope.update = function(user)
{
User.update(user);
$scope.$broadcast('refresh-users');
return true;
}
});
UsersController:
angular.module('myApp')
.controller('UsersController', function($scope, User, ngDialog){
var loadUsers = function(users) {
$scope.users = users;
}
var handleErrors = function(response) {
console.error(response)
}
$scope.userPopup = function(id)
{
ngDialog.open(
{
template:'../partials/user.html',
controller: 'UserController',
data: {'id': id},
scope: $scope
});
}
$scope.$on('refresh-users', function handler(){
console.log('handler');
User.getAll()
.then(loadUsers)
.catch(handleErrors);
});
});
How could I solve this?
Use $rootScope instead of $scope as these two controllers are not using the same scope.
As has already been mentioned you want to use $rootScope for broadcasting if what you're trying to communicate is on another scope.
User Controller
angular.module('myApp')
.controller('UserController', function($scope, $rootScope, User){
//this method gets fired when the dialog is saved
$scope.update = function(user)
{
User.update(user);
$rootScope.$broadcast('refresh-users');
return true;
}
});
UsersController:
angular.module('myApp')
.controller('UsersController', function($scope, $rootScope, User, ngDialog){
var loadUsers = function(users) {
$scope.users = users;
}
var handleErrors = function(response) {
console.error(response)
}
$scope.userPopup = function(id)
{
ngDialog.open(
{
template:'../partials/user.html',
controller: 'UserController',
data: {'id': id},
scope: $scope
});
}
$rootScope.$on('refresh-users', function handler(){
console.log('handler');
User.getAll()
.then(loadUsers)
.catch(handleErrors);
});
});

Angular $q and $http for data binding not working

I'm trying to make a basic data pulling using a service and print it on screen when I have data, but something is not working.
My service:
mymodule.factory('MyService', function($http, $q) {
var service = {
getData: function() {
var dfd = $q.defer();
$http.get(apiServerPath).success(function (data) {
dfd.resolve(data);
});
return dfd.promise;
}
}
return service
}
My Controller:
mymodule.controller('myCtrl', ['$scope', 'MyService', function($scope, MyService) {
$scope.myvar = MyService.getData();
}
HTML
<div> {{myvar}} </div>
What I can see from the browser console -
The myvar object turn into a promise object
The success function is being called and 'data' has valid data in it
And for my question and issue - the controller's variable does not change when the defer object is resolving - why?
Promises are no longer auto-unwrapped as of Angular 1.2. In your controller do the following:
mymodule.controller('myCtrl', ['$scope', 'MyService', function($scope, MyService) {
MyService.getData().then(function success(data) {
$scope.myvar = data;
});
}

Controller not fetching service data

I have a Service and a Controller. The controller calls a function, getItems() on the Service. The Service returns an array of data.
However, the controller appears to not be receiving this, oddly enough.
Controller:
ItemModule.controller('ItemController', ['$scope', 'ItemService',
function ($scope, ItemService) {
$scope.items = [];
$scope.getItems = function() {
$scope.items = ItemService.getItems();
}
$scope.getItems();
}
]);
Service:
ItemModule.service('ItemService', ['$rootScope', '$http',
function($rootScope, $http) {
this.getItems = function() {
$http.get($rootScope.root + '/products').success(function(data) {
// This prints it out fine to the console
console.log(data);
return data;
});
}
}
]);
What am I doing wrong?
A quick and dirty fix would be like that:
ItemModule.service('ItemService', ['$rootScope', '$http',
function($rootScope, $http) {
return {
getItems : function(scope) {
$http.get($rootScope.root + '/products').success(function(data) {
scope.items = data;
});
}
}
}
]);
and then in your controller just call:
ItemService.getItems($scope);
But if your controller is a part of route (and probably is) it would be much nicer to use resolve (look here).

Resources