calling a service inside a controller in angularjs - angularjs

I'm working with ng-resource to do CRUD manipulations as following :
app
.factory('candidatureService',['$resource',
function ($resource) {
return $resource('http://localhost:8080/candidature/candidats', {}, {
update: { method: "PUT"}
});
}]);
I only need PUT in my case.
and in the controller I have this :
app
.controller('CandidatureStartCtrl', function ($scope, candidatureService) {
$scope.candidature = {};
$scope.candidature.guarantor = {};
$scope.submitForm1 = function(isValid) {
console.log('validate form');
// check to make sure the form is completely valid
if (isValid) {
console.log('form 1 is amazing');
console.log($scope.user);
candidatureService.update({},{
"username": "Uchiha",
"nom": $scope.candidature.lastname,
"prenom": $scope.candidature.firstname,
"nomarab": $scope.candidature.arabicLastname,
"prenomarab": $scope.candidature.arabicFirstname,
"genre": $scope.candidature.gender,
"dateNaissance": $scope.candidature.birthdate,
"email": $scope.candidature.email,
"telephone": $scope.candidature.phoneNumber,
"photo": $scope.candidature.photo,
"cin": $scope.candidature.identityDocumentCode,
"adresse": $scope.candidature.address,
"codeMassar": $scope.candidature.codeMassar,
"lieuNaissance": $scope.candidature.placeOfBirth,
"cinPhoto": $scope.candidature.identityDocument,
"anneebac": $scope.candidature.anneebac,
"nomGarant": $scope.candidature.guarantor.fullName,
"lienGarant": $scope.candidature.guarantor.link,
"telephoneGarant": $scope.candidature.guarantor.phoneNumber,
"province": {
"codeProvince" : $scope.candidature.province
}
});
$scope.steps.step2=true;
} else {
console.log('form is invalid');
}
};
});
username is the primary key in my case.
but when I use this controller I'm getting this error message :
TypeError: candidatureService.update is not a function
at new <anonymous> (http://localhost:8080/app/scripts/controllers/candidature-start.js:106:24)
in my index.html I've declared the controller and the service as following :
<script src="scripts/controllers/candidature-start.js"></script>
<script src="scripts/service/candidatureService.js"></script>
and when I access to my page I call the 'CandidatureStartCtrl' which is declared in candidature-start.js :
.state('candidature.start', {
url: '/start',
controller : 'CandidatureStartCtrl',
templateUrl: 'views/tmpl/frontend/candidature-start.html',
containerClass: 'hz-menu',
resolve: {
plugins: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load([
'scripts/vendor/slider/bootstrap-slider.js',
'scripts/vendor/touchspin/jquery.bootstrap-touchspin.js',
'scripts/vendor/touchspin/jquery.bootstrap-touchspin.css',
'scripts/vendor/filestyle/bootstrap-filestyle.min.js'
]);
}]
}
})
So why I'm getting that error message it took me 3 hours but I couldn't figure out whats the problem !

Method names in your services get prepended with a $ when you use $resource, so the call should be to candidatureService.$update

Related

call plugin template /page with script ui.route angularjs?

Hey all can you help me, i want to call css and jquery file for template but one page, i have made it but it does not show its page and plugin file has been called!!
this function app.constant for call a plugin
{
app.constant('MODULE_CONFIG', [
{
name: 'alumnss',
module: true,
files: [
'public/alumni/css/icomoon.css',
'public/alumni/css/simple-line-icons.css',
'public/alumni/css/magnific-popup.css',
'public/alumni/css/owl.carousel.min.css',
'public/alumni/css/owl.theme.default.min.css',
// 'public/alumni/css/salvattore.css',
'public/alumni/css/style.css',
'public/alumni/js/modernizr-2.6.2.min.js',
'public/alumni/js/jquery.easing.1.3.js',
'public/alumni/js/jquery.waypoints.min.js',
'public/alumni/js/jquery.magnific-popup.min.js',
'public/alumni/js/owl.carousel.min.js',
'public/alumni/js/jquery.countTo.js',
'public/alumni/js/main.js'
]
}
]).config(['$ocLazyLoadProvider', 'MODULE_CONFIG', function($ocLazyLoadProvider, MODULE_CONFIG) {
$ocLazyLoadProvider.config({
debug: false,
events: false,
modules: MODULE_CONFIG
});}]);}
2. this route a page
app.config(function($stateProvider, $urlRouterProvider, MODULE_CONFIG) {
$urlRouterProvider.otherwise('/alumnis');
$stateProvider
.state('alumnis', {
url: '/alumnis',
templateUrl: 'alumni.html',
controller:'',
resolve: load(['alumnss']) // **THIS CALL FROM 'MODULE_CONFIG' has been called, But the html page not showing **
})
function load(srcs, callback) {
return {
deps: ['$ocLazyLoad', '$q',
function( $ocLazyLoad, $q ){
var deferred = $q.defer();
var promise = false;
srcs = angular.isArray(srcs) ? srcs : srcs.split(/\s+/);
if(!promise){
promise = deferred.promise;
}
angular.forEach(srcs, function(src) {
promise = promise.then( function(){
angular.forEach(MODULE_CONFIG, function(module) {
if( module.name == src){
if(!module.module){
name = module.files;
}else{
name = module.name;
}
}else{
name = src;
}
});
return $ocLazyLoad.load(name);
} );
});
deferred.resolve();
return callback ? promise.then(function(){ return callback(); }) : promise;
}]
}
}
});
and this image, for page blank not show the template, or something wrong with the code??? help me please???
I have gotten your solution
Change the ocLazyLoad CDN like this
<script data-require="oclazyload#1.0.9" data-semver="1.0.9" src="https://cdnjs.cloudflare.com/ajax/libs/oclazyload/1.1.0/ocLazyLoad.min.js"></script>
and write the code for JQ_CONFIG not MODULE_CONFIG
var app = angular.module('routerApp');
app.constant('JQ_CONFIG', {
callplugincss: [
'style.css'
]
});
app.constant('MODULE_CONFIG', [{
name: 'ngGrid',
module: true,
files: [
'js of ng grid'
]
}]);
and change in dependency
routerApp.config(function ($stateProvider, $urlRouterProvider, MODULE_CONFIG, JQ_CONFIG) {
I think it will work. thanks.

Pass parameter from controller to services in angularjs

How can i have one service or factory receiving two parameters from many controllers?
One parameter for the url, other for the file name to be stored on the filesystem.
I will have many controllers using this service, each passing his own url and filenames that reads the url and generate a pdf.
I will always store the last downloaded pdf providing an "open last pdf" button, that will use the name parameter.
I will have a "generate new pdf" button coming from the url.
I do follow this tutorial https://blog.nraboy.com/2014/09/manage-files-in-android-and-ios-using-ionicframework/ and everything works fine.
I am using cordova file-transfer and inappbrowser cordova plugins
These sections will receive the parameters :
dirEntry.getFile("pdf-number-1.pdf",
ft.download(encodeURI("http://www.someservice.com"),p,
My attempt always trigger the message unknow pdfService provider
Wich concepts of angular i am missing ? How can i fix it ?
In services.js i have :
.service('pdfService', function($scope, $ionicLoading){
if( window.cordova && window.cordova.InAppBrowser ){
window.open = window.cordova.InAppBrowser.open;
console.log("InAppBrowser available");
} else {
console.log("InAppBrowser not available");
}
this.download = function() {
$ionicLoading.show({
template: 'Loading...'
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
fs.root.getDirectory("ExampleProject",{create: true},
function(dirEntry) {
dirEntry.getFile(
"pdf-number-1.pdf",
{
create: true,
exclusive: false
},
function gotFileEntry(fe) {
var p = fe.toURL();
fe.remove();
ft = new FileTransfer();
ft.download(
encodeURI("http://www.someservice.com"),
p,
function(entry) {
$ionicLoading.hide();
$scope.imgFile = entry.toURL();
},
function(error) {
$ionicLoading.hide();
alert("Download Error Source -> " + error.source);
},
false,
null
);
},
function() {
$ionicLoading.hide();
console.log("Get file failed");
}
);
}
);
},
function() {
$ionicLoading.hide();
console.log("Request for filesystem failed");
});
}
this.load = function() {
$ionicLoading.show({
template: 'Loading...'
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
fs.root.getDirectory(
"ExampleProject",
{
create: false
},
function(dirEntry) {
dirEntry.getFile(
"pdf-number-1.pdf",
{
create: false,
exclusive: false
},
function gotFileEntry(fe) {
$ionicLoading.hide();
$scope.imgFile = fe.toURL();
alert(fe.toURL());
window.open(fe.toURL(), '_system', 'location=no,toolbar=yes,closebuttoncaption=Close PDF,enableViewportScale=yes');
},
function(error) {
$ionicLoading.hide();
console.log("Error getting file");
}
);
}
);
},
function() {
$ionicLoading.hide();
console.log("Error requesting filesystem");
});
}
});
And in the controller :
.controller('SomeCtrl', function($scope, $ionicPopup, pdfService) {
...
pdfService.download = function(url) {
console.log('pdfService download');
}
pdfService.load = function() {
console.log('pdfService load');
}
You will need to inject the service to your controllers and call a function with the two params you want as your arguments.
eg.
.service('pdfService', function(){
var lastUrl;
var lastFileName
return {
createPdf(url, fileName){
//do processing
lastUrl = url;
lastFileName = fileName
},
loadLastPdf(){
//use lastUrl and lastFileName
}
}
}
and in your controller:
.controller('SomeCtrl', function(pdfService) {
pdfService.createPdf('http://example.com', 'file.pdf');
// or pdfService.loadLastPdf();
}
That being said, the error you are reporting means that the DI is unable to find a service with the name pdfService to inject to your controller. This might be because you forgot to include the service.js file to your html as a script tag (if you are doing it like that) or you forgot to add it as a dependency using require (if you are using sth like browserify) or maybe if you are minifying your code since you are not using the minsafe syntax

Restangular: first call returns array but subsequent calls return object

I have a AngularJS factory 'UserSrvc'. This is responsible for calling a RESTful back end to get and create user accounts using Restangular:
(function () {
'use strict';
angular
.module('myapp')
.factory('UserSrvc', UserSrvc);
function UserSrvc(Restangular) {
return {
getAllUsers: getAllUsers,
getUser: getUser,
saveUser: saveUser
};
/////////////////////
function getAllUsers(){
return Restangular.all('users').getList();
}
function getUser(user){
return Restangular.setFullResponse(true).one('users', user).get();
}
function saveUser(user) {
return Restangular.all('users').post(user);
}
};
})();
My User controller then has functions for initializing the data for loading in to Angular UI Grid as well as functions for saving a user and getting user data:
(function () {
'use strict';
var controllerId = 'UserCtrl';
// Define the controller on the module
// Inject the dependencies.
// Point to the controller definition function.
angular
.module('myapp')
.controller(controllerId, UserCtrl, ['UserSrvc', 'ngDialog', '$log', 'toaster']);
function UserCtrl(UserSrvc, ngDialog, $log, toaster){
// Using the 'Controller As' syntax, so we assign to the vm variable (for view model).
var vm = this;
var allUsers = [];
// Bindable properties and functions are placed on vm.
vm.activate = activate;
vm.allUsers = {};
vm.toggleForm = false;
vm.saveUser = saveUser;
vm.gridOptions = {
data: allUsers,
enableSorting: true,
enableColumnResizing: true,
enableGridMenu: true,
showGridFooter: true,
showColumnFooter: true,
enableFiltering: true,
columnDefs: [
{name: 'firstName', field: 'First'},
{name: 'lastName', field: 'Last'},
{name: 'login', field: 'Login'},
{name: 'email', field: 'Email'}
]
};
activate();
function activate() {
return getUsers().then(function() {
// User Controller is now activated
$log.info('UserCtrl activated');
});
}
function refreshUserTable() {
return UserSrvc.getAllUsers()
.then(function(data) {
// User table refresh
vm.gridOptions.data = data.data;
$log.info('User table data refreshed.', vm.gridOptions.data);
});
}
function getUsers() {
return UserSrvc.getAllUsers()
.then(function (data) {
$log.debug('data: ', data);
vm.gridOptions.data = data;
//allUsers = data;
$log.debug('allUsers: ', vm.gridOptions.data);
return vm.gridOptions.data;
},
function(response) {
$log.debug("Failed to get users, error with status code", response.status);
});
}
function saveUser(vm) {
var new_user = {
"user": {
"First": vm.user.firstname,
"Last": vm.user.surname,
"Login": vm.user.username,
"Password": vm.user.password,
"Email": vm.user.email
}
};
//$log.debug('The user to be saved: ', user);
return UserSrvc.saveUser(new_user)
.then(function (data) {
$log.debug('The user to be saved: ', new_user);
$log.debug('response: ', data);
// Refresh the table
refreshUserTable(vm);
// Reset the user form
resetForm();
// Close the form
vm.toggleForm = !vm.toggleForm;
// Success toast
toaster.pop("success","User saved", "User '" + new_user.user.Login + "' successfully created");
return data;
},
function(response) {
$log.debug("Failed to save user, error with status code", response.status);
toaster.pop("error", "Unable to save user", "Failed to save user, error with status code " + response.status);
});
}
}
})();
On the first call to UserSrvc.getAllUsers() in the getUsers() function the data parameter from the .then(function(data) returns an array like so:
[
{
"Last": "Jobs",
"Email": "test#example.com",
"Login": "jobs",
"id": 1,
"First": "Steve"
}
]
However, subsequent calls made by refreshUserTable() to the same UserSrvc.getAllUsers(), the data parameter from .then(function(data)) returns an object like so:
{
"data": [
{
"Last": "Jobs",
"Email": "test#example.com",
"Login": "jobs",
"id": 1,
"First": "Steve"
}
]
}
To get it to work I need to pull the data array from the data object by doing data.data.
Why is it that subsequent calls made by the refreshUserTable() return an object and not an array? My suspicion is that it has something to do with the way in which I'm using Restangular or is there something glaringly obvious I've missed?
Ideally I'd like to get rid of the refreshUserTable() function and just use the getAllUsers() to refresh the table.
you set setFullResponse to true which extend your response object. You confused because Restangular uses same property key with you data.
If you want to use full response specifically on one method just use withConfig method of Restangular.
Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setFullResponse(true);
});

AngularJS, ocLazyLoad & loading dynamic States

app
define(['angular', 'angular-ui-router', 'ocLazyLoad', 'config/common',
'layout/services/menuService'],
function(angular) {
'use strict';
var $stateProviderRef = null;
var $urlRouterProviderRef = null;
return angular.module('app', ['ui.router', 'oc.lazyLoad', 'app.common', 'app.layout']);
});
app.config
define(['app'],function(app){
app.config(function($locationProvider, $stateProvider, $urlRouterProvider, $ocLazyLoadProvider) {
$urlRouterProviderRef = $urlRouterProvider;
$stateProviderRef = $stateProvider;
$urlRouterProviderRef.otherwise('/');
$locationProvider.html5Mode({enable: true, requireBase: false}); //.hashPrefix('!');
$ocLazyLoadProvider.config({
events: true,
debug: false
}); }); });
app.run
define(['app'],function(app) {
app.run(function ($q, $rootScope, $state, $window, menuSvc) {
menuSvc.all().success(function(viewStates) {
var startUp = undefined;
angular.forEach(viewStates, function(viewState, key){
var viewStateUrl = undefined;
if (viewState.isStartUp == true && startUp == undefined) {
startUp = viewState.name;
}
var state = {
"url": viewState.url,
"name": viewState.name,
"views": []
}
angular.forEach(viewState.views, (function(view) {
var myView = {
"controller" : view.controller,
"templateUrl" : view.templateUrl,
"resolve" : { }
};
myView.resolve.loadController = function($ocLazyLoad)
{
return $ocLazyLoad.load(
{
"name": view.moduleName,
"files": view.controllerFiles
})
};
state.views[view.viewName] = myView ;
}));
$stateProviderRef.state(viewState.name, state);
})
$state.go(startUp);
})
}); });
Solved:
The error was in a combination of areas. The complete solution is below. I am not happy about the solution to this outcome as mentioned below and welcome ideas. Basically I would have preferred a more agnostic binding of the resolve method to my states in the app.run file.
I have this working, although I am not quite happy with the code and I will explain at the end. First off, I found a path to my solution from this Stackoverflow Prior Question
1. app.js
The only change I made from above was to add the ShellCtrl location:
define(
[
'angular', 'angular-ui-router', 'ocLazyLoad', 'config/common',
'layout/services/menuService', 'layout/controllers/ShellCtrl'],
.....
2. app.config:
Nothing changed from above.
3. app.run
define(['app'],function(app) {
app.run(function ($q, $rootScope, $state, $window, menuSvc) {
menuSvc.all().success(function(states) {
angular.forEach(states, function (state) {>
try{
/// for the Header
state.views.header.resolve[state.views.header.data.controllerAlias] =
function($ocLazyLoad){
return $ocLazyLoad.load({
"name": state.views.header.data.controllerAlias,
"files": state.views.header.data.controllerFiles})};
/// for the Footer
state.views.footer.resolve[state.views.footer.data.controllerAlias] =
function($ocLazyLoad){
return $ocLazyLoad.load({
"name": state.views.footer.data.controllerAlias,
"files": state.views.footer.data.controllerFiles})};
}catch(e){
}
console.log(state);
$stateProviderRef.state(state.name, state);
})
$state.go('app.dashboard');
})
}); });
4. With this as my JSON:
[ { "name": "app", "abstract": true, "url": "", "templateUrl": "app/layout/views/tpl.shell.html", "controller": "ShellCtrl" }, {
"name": "app.dashboard",
"views": {
"header": {
"templateUrl": "app/layout/views/tpl.header.html",
"controller": "HeaderCtrl as header",
"resolve": {},
"data": {
"controllerAlias": "app.layout",
"controllerFiles": [
"app/layout/layout.module.js",
"app/layout/controllers/HeaderCtrl.js"
]
}
},
"footer": {
"templateUrl": "app/layout/views/tpl.footer.html",
"controller": "FooterCtrl as footer",
"resolve": {},
"data": {
"controllerAlias": "app.layout",
"controllerFiles": [
"app/layout/layout.module.js",
"app/layout/controllers/FooterCtrl.js"
]
}
}
} }]
5. Shell.html
<div data-ng-controller="ShellCtrl">{{shell.pageTitle}}
<div data-ui-view="header"></div>
<div data-ui-view="footer"></div>
</div>
6 Sample Controller:
angular.module('app.layout').controller('HeaderCtrl', HeaderCtrl);
/* #ngInject */
function HeaderCtrl($scope) {
var header = this;
header.pageTitle = 'Response coming from HeaderCtrl';
}
7. With this as the output:
What I do not like:
All components of my dashboard are interchangeable. Nothing is static. Depending on the "overall" view, the Header, Footer, SideMenu and Content all change. The link I mentioned above had only 1 interchangeable part, "the Feature" which I assume was main content.
I do not like the fact that I had to hard code each view in the my app.run relative to binding the resolve to each.
If someone knows how I can make this more agnostic, I would greatly appreciate input.
All components of my dashboard are interchangeable. Nothing is static. Depending on the "overall" view, the Header, Footer, SideMenu and Content all change. The link I mentioned above had only 1 interchangeable part, "the Feature" which I assume was main content.
I do not like the fact that I had to hard code each view in the my app.run relative to binding the resolve to each.
If someone knows how I can make this more agnostic, I would greatly appreciate input.
To make this more agnostic, you could implement something more along the lines of this.
Use object properties to iterate each and attempt to load into the respective resolve. Adding more error handling and checks would also help with stability.
3. app.run
define(['app'],function(app) {
app.run(function ($q, $rootScope, $state, $window, menuSvc) {
menuSvc.all().success(function(states) {
angular.forEach(states, function (state) {>
try{
/// try to load for each each view
for (var view in state.views)
{
if (state.views[view]['data']){
state.views[view].resolve[state.views[view].data.controllerAlias] =
function($ocLazyLoad){
return $ocLazyLoad.load({
"name": state.views[view].data.controllerAlias,
"files": state.views[view].data.controllerFiles
}
)};
}
}
}catch(e){
}
console.log(state);
$stateProviderRef.state(state.name, state);
})
$state.go('app.dashboard');
})
}); });

Issue with pre-populating angular-ui's select2

I have an issue with angular-ui/select2 control.
I would like to use angularjs to pre-populate the control with an array of objects. I use the init function in order to try and achieve this but somehow, the view does not get updated on the page...
Here the client module:
angular.module('searchEngineModule', ['ng', 'languageChooserModule','geolocationModule','currentMemberAddressModule', 'addressAutocompleteModule'])
.factory('searchEngineService', function(){
})
.controller('searchEngineCtrl', [ '$scope', '$http', 'languageChooserService', 'retrieveDefaultLanguagesService', 'geolocationService', 'currentMemberAddressService', 'addressAutocompleteService','addressFromReferenceService', function geolocationCtrl($scope, $http, languageChooserService, retrieveDefaultLanguagesService, geolocationService, currentMemberAddressService, addressAutocompleteService, addressFromReferenceService) {
$scope.searchCriteria = {};
$scope.languageChooser = languageChooserService;
$scope.addressAutocomplete = addressAutocompleteService;
$scope.init = function() {
retrieveDefaultLanguagesService.defaultLanguages().then(function(languages){
$scope.searchCriteria.languages = [{}];
$scope.searchCriteria.languages= languages;//HERE: it does populate the model but the view is not updated...
});
geolocationService.geolocationAddress().then(function(address) {
$scope.geolocationAddress = {};
$scope.geolocationAddress = address;
});
currentMemberAddressService.currentMemberAddress().then(function(address){
$scope.currentMemberAddress = {};
$scope.currentMemberAddress = address;
});
};
$scope.$watch('addressAutocomplete', function (newVal, oldVal) {
if (oldVal == newVal) return;
$scope.onTheFlyAddress = {};
if(newVal){
addressFromReferenceService.addressFromReference(newVal.reference).then(function(address){
$scope.onTheFlyAddress = address;
});
}
}, true);
$scope.performSearch = function(){
console.log('performSearch');
console.log($scope.searchCriteria);
};
}])
.config(function($httpProvider) {
$httpProvider.defaults.headers.common['Content-Type'] = 'application/json';
$httpProvider.defaults.headers.common['X-Ajax'] = 'true';
});
Here is the languageChooserModule:
angular.module('languageChooserModule', ['ng', 'ui.select2'])
.factory('languageChooserService', function(){
return select2Options();
})
.factory('retrieveDefaultLanguagesService', ['$http', '$q', function($http, $q){
function retrieveDefaultLanguagesP(){
var deferred = $q.defer();
var defaultLanguages = [{}];
$http.get('/bignibou/utils/findLanguagesByLanguageStartingWith.json', {params:{language: 'fran'}})
.success(function(languages){
defaultLanguages = languages;
deferred.resolve(defaultLanguages);
});
return deferred.promise;
}
return{
defaultLanguages: function(){
return retrieveDefaultLanguagesP();
}
};
}]);
function select2Options(){
function format(item) {
return item.description;
}
return {
simple_tags: false,
multiple : true,
contentType: "application/json; charset=utf-8",
minimumInputLength : 3,
data:{ text: "description" },
formatSelection: format,
formatResult: format,
ajax : {
url : "/bignibou/utils/findLanguagesByLanguageStartingWith.json",
dataType : 'json',
data : function(term) {
return {
language : term
};
},
results : function(data, page) {
return {
results :
data.map(function(item) {
return {
id : item.id,
description : item.description,
version : item.version
};
}
)};
}
}
};
}
Can anyone please help?
edit 1:
Chaging to the following:
retrieveDefaultLanguagesService.defaultLanguages().then(function(languages){
$scope.searchCriteria.languages = [{}];
$scope.searchCriteria.languages= languages;
$scope.$digest();
});
Causes the following Error:
Error: [$rootScope:inprog] $digest already in progress
http://errors.angularjs.org/1.2.1/$rootScope/inprog?p0=%24digest
at http://localhost:8080/bignibou/js/libs/angular.js:78:12
at beginPhase (http://localhost:8080/bignibou/js/libs/angular.js:11878:15)
at Scope.$digest (http://localhost:8080/bignibou/js/libs/angular.js:11412:9)
at Scope.$delegate.__proto__.$digest (<anonymous>:844:31)
at http://localhost:8080/bignibou/js/custom/searchEngineModule.js:18:12
at wrappedCallback (http://localhost:8080/bignibou/js/libs/angular.js:10597:81)
at http://localhost:8080/bignibou/js/libs/angular.js:10683:26
at Scope.$eval (http://localhost:8080/bignibou/js/libs/angular.js:11576:28)
at Scope.$digest (http://localhost:8080/bignibou/js/libs/angular.js:11421:31)
at Scope.$delegate.__proto__.$digest (<anonymous>:844:31)
edit 2:
Changing to the following:
$scope.$apply(function(){
retrieveDefaultLanguagesService.defaultLanguages().then(function(languages){
$scope.searchCriteria.languages= languages;
});
});
causes the following error:
Error: [$rootScope:inprog] $apply already in progress
http://errors.angularjs.org/1.2.1/$rootScope/inprog?p0=%24apply
at http://localhost:8080/bignibou/js/libs/angular.js:78:12
at beginPhase (http://localhost:8080/bignibou/js/libs/angular.js:11878:15)
at Scope.$apply (http://localhost:8080/bignibou/js/libs/angular.js:11675:11)
at Scope.$delegate.__proto__.$apply (<anonymous>:855:30)
at Scope.$scope.init (http://localhost:8080/bignibou/js/custom/searchEngineModule.js:17:11)
at http://localhost:8080/bignibou/js/libs/angular.js:9885:21
at Scope.$eval (http://localhost:8080/bignibou/js/libs/angular.js:11576:28)
at pre (http://localhost:8080/bignibou/js/libs/angular.js:18210:15)
at nodeLinkFn (http://localhost:8080/bignibou/js/libs/angular.js:6104:13)
at compositeLinkFn (http://localhost:8080/bignibou/js/libs/angular.js:5536:15)
If your return value from retrieveDefaultLanguagesService.defaultLanguages() is a $q.defer().promise then (ha!) then will cause a digest to occur and therefore $apply, so your edits are redundant. If you need to do that in the future (usually rare) you should do it this way:
if(!rootScope.$$phase)rootScope.$apply();
To reduce some complexity I would also suggest removing the initialization of searchCriteria and initializing your object structure within your then success callback. Like this:
retrieveDefaultLanguagesService.defaultLanguages().then(function(languages){
$scope.searchCriteria = {languages:languages};
});
If that doesn't work I might guess that your html is incorrect in some way. if you share it you might find more help.
I'm also using angluarjs 1.2.3 and ui-select2 with no issues
I forgot to mention that I use angular 1.2.1 and according to this post: (https://stackoverflow.com/a/20186141/536299) there appears to be an incompatibility between angular js 1.2 and angular ui select2....

Resources