How to update in ionic - angularjs

Im trying to update my already existing entries using angularjs and ionic.I have two views, in the first view I have listed the car name and its model name. When the car name is selected, it is directed to second view where the information regarding the selected car name and its models are listed so that they are edited and updated.I have declared $rootScope.selectItem=key; which help to show what is the selected car name. I face problem in update so, I need help in updating the information by replacing the new information with old information.
view 1:
<ion-list>
<ion-item ng-model="carBrand" ng-repeat="name in carSelect">
<button ng-click="selectItem(name)">{{name.name}}</button>
<div class="item" ng-repeat="type in name.types">{{type}}</div>
</ion-item>
</ion-list>
view 2:
<input type="text" ng-model="newName"><br> Select Type:{{selectItem}}</div>
<ion-checkbox ng-repeat="field in fields" ng-model="field.checked" ng-checked="field.checked">
{{field.name}}
</ion-checkbox>
<button ng-click="remove()">Delete</button>
<button ng-click="Update()">Update</button></div>
Controller:
carService.controller('carBrand', ['$scope', 'carRepository', '$rootScope', '$state', '$stateParams', function ($scope, carRepository, $rootScope, $state, $stateParams) {
$rootScope.carSelect = carRepository.data;
$scope.newCarList = [];
$scope.selectItem = function (key) {
$rootScope.selectItem=key;
$state.go('app.carModel');
}
carService.controller('carAdd', ['$scope', '$rootScope', '$state', function ($scope, $rootScope, $state) {
$scope.newName = "";
$scope.fields = [{ id: 1, name: 'Regular' },
{ id: 2, name: 'SUV' },
{ id: 3, name: 'Oversize' },
{ id: 4, name: 'Truck' },
{ id: 5, name: 'Motorcycle' }];
$scope.sample = [];
$scope.Update = function () {
var carType = [];
....}

If I were you, I would change some things to make it more application-like.
First of all, change your state routing:
$stateProvider.state("app.carModel", {
// ..
url: "edit/:id"
}
Then in your selectedItem function:
$scope.selectItem = function (car) {
// assuming your cars have an id property
// you can ofcourse also use something else
$state.go('app.carModel', { id: car.id });
}
Then in your edit/add controller:
carService.controller('carAdd', ['$scope', '$stateParams', 'carRepository', function ($scope, $stateParams, carRepository) {
var carId = $stateParams.id;
// make a copy, so it only gets changed in the repository when the user
// presses 'Update'
$scope.car = angular.copy(carRepository.get(carId));
$scope.fields = [{ id: 1, name: 'Regular' },
{ id: 2, name: 'SUV' },
{ id: 3, name: 'Oversize' },
{ id: 4, name: 'Truck' },
{ id: 5, name: 'Motorcycle' }
];
$scope.sample = [];
$scope.Update = function () {
// ..
// in the save function replace the existing with the edited
carRepository.save($scope.car);
}
}

Related

AngularJS - Watch filtered list for changes

Within angular I have a filtered list of people that takes the filter criteria from a predicate function. I want to watch a variable of the filtered list (called filteredPeople) every time the filtered list changes. But I am unable to see when that variable changes.
My code is below:
HTML:
<ul>
<li ng-repeat="person in ($ctrl.filteredPeople = ($ctrl.people | filter: $ctrl.filter))">
...
</li>
</ul>
JS:
controller: ['$scope',
function ($scope) {
var $ctrl = this;
$ctrl.people = {...}
$ctrl.filteredPeople = [];
$scope.$watch($ctrl.filteredPeople, function () {
console.log("called"); //not being called
});
$ctrl.filter = function (p) {
//custom filter function for each item in the array of people
}
}]
I can answer any questions of provide more code if needed
angular.module('app', []).controller('ctrl', function($scope) {
var vm = this;
vm.items = [
{ name: 'Sam' },
{ name: 'Max' },
{ name: 'Tom' },
{ name: 'Henry' },
{ name: 'Jack' },
{ name: 'Kate' }
]
var counter = 1;
$scope.$watchCollection('vm.filtered', function(){
console.log('Changed' + counter++);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<div ng-app='app' ng-controller='ctrl as vm'>
<input type='text' ng-model='vm.filter' />
<ul>
<li ng-repeat='item in vm.filtered = (vm.items | filter : vm.filter)'>{{item}}</li>
</ul>
</div>

Angular. Pass data from component to parent controller

Hot to recive data from component in parent controller.
I have this code:
index.html
<div ng-controller="formController">
<phones-list phone="phone"></phones-list>
<button ng-click="saveForm()">Save</button>
</div>
form.controller.js
var app = angular.module('myApp');
app.controller('formController', ['$scope', function($scope) {
$scope.saveForm = function() {
console.log($scope.phone)
}
}]);
phoneList.component.js
var app = angular.module('myApp');
app.component('phonesList', {
templateUrl: '/scripts/components/phones/phonesList.template.html',
controller: 'phonesListController',
bindings: {
phone: '='
}
});
phoneList.template.html
<select name="" id="" ng-change="$ctrl.change()" ng-model="$ctrl.phone">
<option ng-repeat="phone in $ctrl.phones">{{ phone.name }}</option>
</select>
phoneList.controller.js
var app = angular.module('myApp');
app.controller('phonesListController', function() {
this.phones = [
{
name: 'ABC',
number: '723-543-122'
},
{
name: 'ABCDE',
number: '324-531-423'
}
];
this.change = function() {
console.log(this.phone)
}
});
So I have select list with phones. What I want is to get phone object in formController after select and submit form. For now I get only text value from .
Add an additional binding to your phoneList component with a function to call when the selection changes.
phoneList.component.js
var app = angular.module('myApp');
app.component('phonesList', {
templateUrl: '/scripts/components/phones/phonesList.template.html',
controller: 'phonesListController',
bindings: {
phone: '=',
onChange: '&' //This will allow you to bind a function to your
} //component that you can execute when something
}); //happens
phoneList.controller.js
var app = angular.module('myApp');
app.controller('phonesListController', function() {
this.phones = [
{
name: 'ABC',
number: '723-543-122'
},
{
name: 'ABCDE',
number: '324-531-423'
}
];
this.change = function() {
console.log(this.phone);
this.onChange({phone: phone}); //call our new callback and give it
} //our update
});
index.html
<div ng-controller="formController">
<phones-list phone="phone"
on-change="phoneSelected(phone)">
<!--Tell our component which function we wish to bind to-->
</phones-list>
<button ng-click="saveForm()">Save</button>
</div>
form.controller.js
var app = angular.module('myApp');
app.controller('formController', ['$scope', function($scope) {
$scope.saveForm = function() {
console.log($scope.phone)
}
$scope.phoneSelected(phone){
//Do your stuff here!
}
}]);
I hope that helps!
I found the solution. I changed component template and add ng-options directive to . I don't know why it is more diffucult to do the same in standard list.
index.html
<div ng-controller="ProposalController">
<phones-list phone="phone"></phones-list>
<button ng-click="saveForm()">Zapisz</button>
</div>
phoneList.component.js
var app = angular.module('myApp');
app.component('phonesList', {
templateUrl: '/components/phones/templates/phoneList.template.html',
controller: 'PhoneListController',
bindings: {
phone: '='
}
});
phoneList.controller.js
....
this.change = function() {
this.phone = this.selectedPhone;
}
....
phoneList.template.html
<select ng-model="$ctrl.selectedPhone" ng-change="$ctrl.change()" ng-options="phone.name for phone in $ctrl.phones"></select>
form.controller.js
$scope.saveForm = function(){
console.log($scope.phone)
}

AngularJS NG-Repeat Seems to Not Work on Array with Single Object

I have found many posts about how ng-repeat does not play well with objects, and expects the data to be an array, but my data is an array, it just happens to have a single object(list2). I get list1 fine, and everything works perfect. According to everything that I have found, list2 should work. Anyone know why it doesn't?
Data coming from my factory:
(function(){
var Factory = function(){
var model = {
list1: [
{
id: "1_1",
type: "header",
headerText: "1_1 Header",
secondaryHeaderText: "",
paragraphText: "1_1 Paragraph",
image: ""
},
{
id: "1_2",
type: "header",
headerText: "Header 1_2",
secondaryHeaderText: "",
paragraphText: "1_2 Paragraph",
image: ""
},
{
id: "1_3",
type: "header",
headerText: "1_3 Header1",
secondaryHeaderText: "1_3 Header2",
paragraphText: "",
image: ""
}
],
list2: [
{
id: "2_1",
type: "link",
headerText: "2_1 Header",
paragraphText: "2_1 Paragraph",
linkText: "2_1 Link Text",
image: ""
}
]
};
var factory = {};
factory.getList1 = function(){
return model.list1;
};
factory.getList2 = function(){
return model.list2;
};
return factory;
};
angular.module('designApp').factory('Factory', Factory);
}());
HMTL
<div>
<!--works perfectly fine -->
<div ng-repeat="item in list1" ng-include="'app/partial/list1.html'"></div>
</div>
<div>
<div ng-repeat="item in list2" ng-include="'app/partial/list2.html'"></div>
</div>
Controller
(function(){
var Controller = function($scope, Factory){
$scope.list1 = [];
$scope.list2 = [];
function init(){
$scope.list1 = Factory.getList1();
$scope.list2 = Factory.getList2();
}
init();
};
Controller.$inject = ['$scope', 'Factory'];
angular.module('designApp')
.controller('Controller', Controller);
}());
This is all that is in list2.html. Does not render any of the model data but renders the html tags, and throws no errors.
<h2>{{list2.headerText}}</h2>
<p>{{list2.paragraphText}}</p>
Thanks in advance for any help!
You have to replace
<h2>{{list2.headerText}}</h2>
<p>{{list2.paragraphText}}</p>
by
<h2>{{item.headerText}}</h2>
<p>{{item.paragraphText}}</p>
working plunkr:
https://plnkr.co/edit/FC5KPpOl7gsmfva63veq?p=preview

ionic/AngularJs transfer data between views

I'm trying to transfer data between two views. I followed the example on http://learn.ionicframework.com/formulas/sharing-data-between-views/ but can't seem to get it right.
essentially my app.js is:
.state('friends', {
url: '/friends',
templateUrl: 'templates/friends.html',
controller: 'FriendsCtrl'
})
.state('friend-detail', {
url: '/friends/:friendId',
templateUrl: 'templates/friend-detail.html',
controller: 'FriendDetailCtrl'
});
In friends.html I have a list of my friends and I am trying to pass the id to friend-detail.html. Here is the content of friends.html:
<ion-content>
<ion-list>
<ion-item class="item-avatar" ng-repeat="friend in friends" ng-href='#/friends/{{friend.id}}'>
<img ng-src="{{friend.face}}">
<h2>{{friend.name}}</h2>
</ion-item>
</ion-list>
</ion-content>
and I am looking for friend.id or friend.name in friend-detail.html. I am able to use {{friend.id}} in friends.html to test and it's working but can't get to new page.
Here is my list just incase:
.factory('Friends', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
// Some fake testing data
var friends = [{
id: 0,
name: 'Ben Sparrow',
notes: 'Enjoys drawing things',
face: 'https://pbs.twimg.com/profile_images/514549811765211136/9SgAuHeY.png'
}, {
id: 1,
name: 'Max Lynx',
notes: 'Odd obsession with everything',
face: 'https://avatars3.githubusercontent.com/u/11214?v=3&s=460'
}, {
id: 2,
name: 'Andrew Jostlen',
notes: 'Wears a sweet leather Jacket. I\'m a bit jealous',
face: 'https://pbs.twimg.com/profile_images/491274378181488640/Tti0fFVJ.jpeg'
}, {
id: 3,
name: 'Adam Bradleyson',
notes: 'I think he needs to buy a boat',
face: 'https://pbs.twimg.com/profile_images/479090794058379264/84TKj_qa.jpeg'
}, {
id: 4,
name: 'Perry Governor',
notes: 'Just the nicest guy',
face: 'https://pbs.twimg.com/profile_images/491995398135767040/ie2Z_V6e.jpeg'
}];
return {
all: function() {
return friends;
},
get: function(friendId) {
// Simple index lookup
return friends[friendId];
}
}
})
and here are the controllers:
FriendsCtrl:
.controller('FriendsCtrl', function($scope, $state, Friends) {
$scope.friends = Friends.all();
});
NewTransfersCtrl:
.controller('NewTransfersCtrl', function($scope, $stateParams, Friends) {
$scope.friend = Friends.get($stateParams.friendId);
})
See sample here : http://codepen.io/aaronksaunders/pen/gbWgQe?editors=101
basically you should be checking for the stateParams.id to get the id being passed on the URL. It would be easier to show you what is missing if you provided more code.

Issue with modifying objects that are added by Angular modal controller

I'm having issue with modifying objects that are adding through angular modal controller
I have
.controller("viewController", function($scope, $modal) {
$scope.allPosts = [
{
id: 1,
owner: "Owner 2",
profile: "images/profile.png",
title: "Book title 1",
image: null,
price: 25,
reply: 2,
fav: 1,
isFaved: false,
content: "test"
},
{
id: 2,
owner: "Owner",
profile: "images/profile2.png",
title: "Ken Follett",
image: "images/book1.jpg",
price: 20,
reply: 12,
fav: 3,
isFaved: true,
content: "The book is in nice"
}
];
$scope.addFav = function(id) {
_.each($scope.allPosts, function(post) {
if(post.id === id) {
post.isFaved = !post.isFaved;
if(post.isFaved) {
post.fav++;
$scope.myFavs.push(post);
} else {
post.fav--;
$scope.myFavs = _.reject($scope.myFavs, function(post) {
return post.id === id;
});
}
}
});
};
$scope.addPost = function() {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
allPosts: function(){
return $scope.allPosts;
}
}
});
};
)
.controller('ModalInstanceCtrl', function ($scope, $modalInstance, allPosts) {
$scope.postId = 50;
$scope.ok = function () {
var temp = {};
temp.id = $scope.postId;
temp.profile = "images/profile.png";
temp.title = $scope.title;
temp.type = $scope.type;
temp.price = $scope.price;
temp.reply = 0;
temp.fav = 0;
temp.isFaved = false;
temp.content = $scope.description;
$scope.allPosts.push(temp);
$scope.postId++;
$modalInstance.close();
};
});
$scope.addFav(id) function works fine with existing $scope.allPosts. However, when I add new object by using the ModalInstanceCtrl, the $scope.allPosts is updated but when it goes to $scope.addFav(id), I can not modified the new object that is pushed in to $scope.allPosts from ModalInstanceCtrl. for example I try to update the fav property in post by using
post.fav++; // console.log(post) shows the fav property is not updated. it remains at 0.
As you don't show the markup I suspect that the ModalInstanceController must be nested within the scope of the viewController. This would explain how the same allPosts is available in both controllers. However the postId will be different on each scope due to the way that javascript's prototypical inheritance works. To overcome this you could define an object on scope something like this:
$scope.posts = {
postId: 0,
allPosts: []
}
Alternatively, and even better imho, define a Posts service that encapsulates all the post behaviours and inject that into both controllers. You are then insulated from any changes to the markup that could muck up the controller inheritance.

Resources