Reload ng-repeat angular / ionic - javascript

I already read some discussions about this problem but no one works for me.
I have a controller
.controller('TestFriendCtrl', ['$scope', 'APIUser', function($scope, APIUser) {
$scope.data.friends = [{username: 'test'}];
$scope.change = function(friend) {
APIUser.find(friend, function(success, data){
if (success) {
$scope.data.friends = data;
console.log($scope.data.friends);
}
})
}
}]);
I also tried
.controller('TestFriendCtrl', ['$scope', '$timeout', 'APIUser', function($scope, $timeout, APIUser) {
$scope.friends = [{username: 'coucou'}];
$scope.change = function(friend) {
APIUser.find(friend, function(success, data){
if (success) {
$timeout(function() {
$scope.friends = data;
console.log($scope.friends);
} );
}
})
console.log($scope.friends);
}
}]);
and
.controller('TestFriendCtrl', ['$scope', '$timeout', 'APIUser', function($scope, $timeout, APIUser) {
$scope.friends = [{username: 'coucou'}];
$scope.change = function(friend) {
APIUser.find(friend, function(success, data){
if (success) {
$scope.friends = angular.copy(data);
}
})
console.log($scope.friends);
}
}]);
In all cases console.log($scope.friends); return the expected value
And a view
<ion-view class="main-page">
<ion-content>
<h1>Friend</h1>
<label class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input ng-model="friend" name="friend" type="search" placeholder="Search" ng-change="change(friend)">
</label>
{{ data.friends[0].username }}
<ion-list ng-controller="TestFriendCtrl" >
<ion-item ng-repeat="friend in data.friends" class="item-thumbnail-left">
<p>{{friend.username}}</p>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
the $scope.friend is well updated in the console output but my list does not change.
I tried to add $scope.$apply but I have $digest already in progress

You could try this, while I don't know what APIUser does:
.controller('TestFriendCtrl', ['$scope', 'APIUser', function($scope, APIUser) {
$scope.friends = [{username: 'test'}];
$scope.change = function(friend) {
APIUser.find(friend).$promise.then(function(success, data){
if (success) {
$scope.friends = data;
console.log($scope.friends);
}
}, function (err) {
console.log(err);
)};
}
}]);

Following your latest update, I assume that may have a link to the . (dot).
There is plenty of post easily foundable in google explaining why it is not goot to have a direct model without a .dot dilimiter.
Try to change your model with $scope.myDatas.friends = data; and change your ng-repeat call to ng-repeat="friend in myDatas.friends"

The comment suggesting angular.copy() was almost correct, it was just missing the second parameter. Using angular.copy() (or similarly Lodash's _.assign()) you wont lose the reference to the original array instance. See this answer or this answer for further explanation.
.controller('TestFriendCtrl', ['$scope', 'APIUser', function($scope, APIUser) {
$scope.friends = [{username: 'test'}];
$scope.change = function(friend) {
APIUser.find(friend).$promise.then(function(success, data){
if (success) {
angular.copy(data, $scope.friends);
console.log($scope.friends);
}
}, function (err) {
console.log(err);
)};
}
}]);

Related

AngularJS - Dynamic parameter in $http URL

The URL I use to retreive a JSON for my app has a dynamic parameter (:id ). I'm not too sure how I can work with this, so that it passes the ID the user has chosen. Just need a bit of guidance.
app.factory('bookcategories', ['$http', function($http) {
return $http.get('http://52.41.65.211:8028/api/v1/categories/:id/books.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
Controller
app.controller('BookCategoryController', ['$scope', 'categories', '$routeParams', function($scope, categories, $routeParams) {
categories.success(function(data) {
$scope.detail = data.categories[$routeParams.bookId];
$scope.currentCategoryIndex = parseInt($routeParams.categoryId);
$scope.myCategoriesDetails = $scope.category;
});
}]);
app.js
...
.when('/categories/:categoryId', {
controller: 'BookCategoryController',
templateUrl: 'views/booksincategory.html'
})
...
HTML
<h3 class="title">{{book.title}}</h3>
You could achieve this with a little service like the following code example. A factory is a wrong choice here.
app.service('bookCategories', ['$http', function($http) {
this.get = function (id) {
return $http.get('http://52.41.65.211:8028/api/v1/categories/'+ id + '/books.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
};
}]);
And than use it like:
app.controller('MyCtrl', function(bookCategories) {
bookCategories.get(1).then(function (result) {
console.log(result);
});
});

AngularJS orderBy issue

Sorry if this sounds dumb.
I'm having a problem similar to this question and while the accepted answer worked, it also brought up another issue: When I add a new object to the array, Angular doesn't render it.
app.controller('MainCtrl', [
'$scope',
'$filter',
'posts',
function($scope, $filter, posts) {
$scope.posts = $filter('orderBy')(posts.posts, '-votes')
}
]
My add function:
o.addPost = function(post) {
return $http.post('/posts', post).success(function(data) {
o.posts.push(data)
})
}
Are there anything I can do about it?
EDIT: I'm going with this:
o.addPost = function(post) {
return $http.post('/posts', post)
}
app.controller('MainCtrl', [
'$scope',
'$filter',
'posts',
function($scope, $filter, posts) {
$scope.posts = $filter('orderBy')(posts.posts, '-votes')
$scope.addPost = function() {
posts.addPost(param).then(function(response) {
$scope.posts.push(response.data)
})
}
]
in the factory just return the http instead of the unwrapping the promise inside the factory
o.addPost = function(post) {
return $http.post('/posts', post);
}
then call the addPost method inside the factory.And catch the promise inside the promise.
app.controller('MainCtrl', [
'$scope',
'$filter',
'posts',
function($scope, $filter, posts) {
var params = {};
posts.addPost(params).then(function(data) {
$scope.posts = $filter('orderBy')(data, '-votes')
})
}
])
angular only trigger for instance changes. If you just modify the array by push or splice, the filter won't be fired.
you can do the following way to give the array a new instance.
o.addPost = function(post) {
return $http.post('/posts', post).success(function(data) {
o.posts.push(data);
o.posts = o.posts.slice(); // this will give array a new instance and fire the filter.
})
}

how to add a factory in ionic?

i'm experimenting with ionic (and building using phonegap online builder) and i'm trying to add a factory now but it messes up and gives a blank white screen. i tried the fix in a similar problem : How to use factories with Ionic/Angular JS with phonegap?
but it still doesnt work. my services.js file looks like this:
.factory('userFactory', [function() {
var users = [
{name: 'Omar', city: 'rizal'},
{name: 'Ganny', city: 'makati'},
{name: 'Chester', city: 'manila'}
];
return {
getUsers: function(){
return users;
},
getUser: function(id){
for(i=0;i<users.length;i++){
if(users[i].name == id)
{
return users[i];
}
}
return null;
}
};
}])
and my controller looks like this:
angular.module('app.controllers', [])
.controller('CityCtrl', ['$scope', '$stateParams', '$location'
function ($scope, $stateParams, $location, userFactory) {
$scope.userdata = {};
$scope.enterCity = function(usern,city) {
if(userFactory.getUser(usern) != null)
{
$location.path('/page14');
}
else
{
alert('Failed');
}
}
}])
Your depdencenies to the controller is not properly formated,It should be
.controller('CityCtrl', ['$scope', '$stateParams', '$location','userFactory',
function ($scope, $stateParams, $location, userFactory) {

Inputting an UUID/GUID into a form's text input using Angular JS

I am creating a form with several input options for the end user, but with one input which I would like to be an UUID/GUID.
Here's what I have so far for the module (project.js):
angular.module('project', ['ngRoute', 'firebase'])
.value('fbURL', 'https://private.firebaseio.com/')
.factory('Projects', function($firebase, fbURL) {
return $firebase(new Firebase(fbURL));
})
.config(function($routeProvider) {
$routeProvider
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html'
})
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.php'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'detail.php'
})
.otherwise({
redirectTo:'/'
});
})
.controller('ListCtrl', function($scope, Projects) {
$scope.projects = Projects;
$scope.project = { trackid: 'UUID' };
})
.controller('CreateCtrl', function($scope, $location, $timeout, Projects) {
$scope.project = { trackid: 'UUID' };
$scope.save = function() {
Projects.$add($scope.project, function() {
$timeout(function() { $location.path('/'); });
});
};
})
.controller('EditCtrl',
function($scope, $location, $routeParams, $firebase, fbURL) {
var projectUrl = fbURL + $routeParams.projectId;
$scope.project = $firebase(new Firebase(projectUrl));
$scope.destroy = function() {
$scope.project.$remove();
$location.path('/');
};
$scope.save = function() {
$scope.project.$save();
$location.path('/');
};
$scope.project = { trackid: 'UUID' };
});
And here's what I have for the form input (in my detail.php file):
<form name="myForm">
<label>Track ID</label>
<input type="text" name="trackid" ng-model="project.trackid" disabled>
As you can tell, in this example I'm simply inserting the text "UUID" where I would actually like to insert an UUID. I can't however seem to figure out how to insert a function there that would be generating this UUID. Any help would be very much appreciated! Thank you!
If you have a function that returns the value needed you can simply do:
function getUUID(){
var result = /* parse value */
return result;
}
$scope.project ={ trackid: getUUID() };
DEMO

Run function of one angular controller in another controller

I have page with 2 lists: categories and products for that category. Module code:
var shop = angular.module('shop', []);
shop.controller('Products', ['$scope', '$http', '$rootScope', function($scope, $http, $rootScope) {
$scope.products = [];
$scope.update = function () {
$http.post('/shop/products', {
category_id: $rootScope.category_id
})
.success(function(response, status){
$scope.products = response.data;
})
.error(function(data, status){ });
};
}]);
shop.controller('Categories', ['$scope', '$http', '$rootScope', function($scope, $http, $rootScope) {
$scope.categories = [
{ name: 'games', id: 1 }, { name: 'films', id: 2 }
]
$rootScope.category_id = '-1';
$scope.select = function (id) {
$rootScope.category_id = id;
// Need to run an update of Product controller
}
}]);
When a user selects the category by clicking on it, I need to update products list with new products (filtered by selected category) that I received from a server. And the question is How to run update function of Products controller in Categories controller?
I know about easy-way with event broadcastings, but it is not the best solution.

Categories

Resources