Im trying to use ionic list to display a set of cars, when the particular car is selected it should display a small description of it and also editable. Here Im unable to display the description of the item selected. Also please let me know how to edit the description and update it.
link here
this is the controller
car.controller('popSelect', ['$scope','$ionicPopup', function ($scope, $ionicPopup) {
$scope.homePage = function () {
window.location = "#/menu.html"
}
$scope.carList = [{ value: "Honda", description: "Its honda" },
{ value: "Toyota", description: "Its Toyota" },
{ value: "BMW", description: "Its BMW" }];
//$scope.carList=['Bmw','Mercedes','Honda'];
$scope.select_item = function (key) {
{{item.decription}}
}
}]);
Changes in Index.html
<body ng-app="myApp" ng-controller="myCtrl">
<h4>Select car</h4>
<ion-list>
<ion-item ng-click="select_item(value)" ng-repeat="(key,value) in carList">
{{value.value}}
</ion-item>
</ion-list><hr>
<div style="text-align:center">
<button class="button3" ng-click="showPopup()">ADD</button><hr>
<button class="button2" ng-click="homePage()">Back</button>
<button class=" button2" ng-click="deleteSelected()">Delete</button>
</div>
<div>{{description}}</div>
<!--{{couponTitle}} {{couponDescribe}} {{validFrom}} {{validTo}} -->
</body>
In your js
var car=angular.module('myApp',[]);
car.controller('myCtrl', ['$scope', function ($scope) {
$scope.homePage = function () {
window.location = "#/menu.html"
}
// $scope.description = '';
$scope.selectedItem = 'select';
$scope.items=[];
$scope.carList = [{ value: "Honda", description: "Its honda" },
{ value: "Toyota", description: "Its Toyota" },
{ value: "BMW", description: "Its BMW" }];
//$scope.carList=['Bmw','Mercedes','Honda'];
$scope.select_item = function (key) {
$scope.description=key.description;
}
}]);
Thanks (Y)
Related
The issue I have occurs when a user enters a category. Categories like electronics, toys, and cars are written using v-if condition. So while we enter these three categories in the category field I don't want to show the radio button checked.
Here I have tried this by using like v-if="(category != 'Electronics')||(category != 'Toys')||(category != 'cars')" this condition but here this "||" condition is not working.
*input field for entering a category*
<div><input type="text" v-model="category" placeholder="Search your category"></div>
<div v-if="(category != 'Electronics')||(category != 'Toys')||(category != 'cars')">
<h1>Consumer</h1>
<div class="radio_select">
<input type="radio" v-model="picked" value="consumer">
<label>Personal Ad:</label>
<p>Personal ads can be posted one ad per month, which will appear with "sale by owner tag"</p><br>
<div>
<input type="radio" id="business" name="flag" value="business" v-model="picked">
<label>Business Ad:</label>
<p>Do you want to upgrade to business account to post more <br>ads per month</p>
<span class="prev_next">
<button class="prev_next_btn" #click.prevent="prev()">Previous</button>
<button class="prev_next_btn" #click.prevent="next()">Next</button>
</span>
</div>
</div>
</div>
vue.js
<script>
Vue.use(VueFormWizard)
new Vue({
el: '#q-vikreya',
components: {
"vue-form-g": VueFormGenerator.component
},
data() {
return {
step:1,
category:'',
model:'',
formOptions: {
validateAfterLoad: true,
validateAfterChanged: true
}
};
},
<!--/ By using this delimiters we were able to fix the vue.js compatibility with django. since the curly braces between django and-->
<!-- // vue.js conflicted, delimiters helped here to solve the conflicts-->
delimiters: ["<%","%>"],
ready: function() {
console.log('ready');
},
methods: {
prev(currentStep) {
if(this.checkForm()) {
if (currentStep === 4) {
this.step = 3
} else {
this.step--;
}
}
},
next(currentStep) {
if(this.checkForm()) {
if (currentStep === 4) {
this.step = 5
} else {
this.step++;
}
}
},
checkForm: function (e) {
if (this.category && this.title) {
return true;
}
this.errors = [];
if (!this.category) {
this.errors.push('Name required.');
}
if (!this.title) {
this.errors.push('Age required.');
}
e.preventDefault();
},
submitForm: function(){
axios({
method : "POST",
url: "{% url 'PostAd' %}", //django path name
headers: {'X-CSRFTOKEN': '{{ csrf_token }}', 'Content-Type': 'application/json'},
data : {"category":this.category, "title":this.title,
"address":this.address,
"city": this.city,
"state": this.state,
"zip": this.zip,
"price": this.price,
"description": this.description,
"radio_price": this.radio_price,
"Job_title": this.model,
},//data
}).then(response => {
console.log("response");
console.log(response.data);
this.success_msg = response.data['msg'];
window.location.replace('{% url "classifieds" %}') // Replace home by the name of your home view
}).catch(err => {
this.err_msg = err.response.data['err'];
console.log("response1");
console.log(err.response.data);
});
},
},
})
</script>
I have to call a POST function, and need to compress the data in web form into an object in advance. I use ng-repeat to display all data input, and init this value for input, but I have no idea how to use ng-model to save the data.
I can resolve this case by setting an dynamic id for input, and using JQuery to get data, but it's not a good solution. And I want use AngularJS model only.
Please give me an advice. Below is my code:
Click here to see the screenshot of UI form
html file
<!-- edit-user-page-view -->
<div spectrum-error-container
data-scope-id="$id"
class="col-sm-12"></div>
<div class="email-preference-block">
<form name="editUserForm"
id="editUserForm"
role="form"
class="prj-form prj-create-user-form">
<fieldset id="fieldsetAccountInformation">
<legend>{{ 'user.userPage.form.fieldsets.accountInformation' | translate }}</legend>
<div class="row language-preference-block">
<div class="form-group">
<div class="col-md-12 col-sm-12">
<label data-translate="user.userPage.form.preferredLanguage"></label>
</div>
<div class="col-md-12 col-sm-12">
<label data-ng-repeat="option in preferencesData.languageOptionList"
class="radio-inline">
<input type="radio"
ng-model="emailNotificationModel.selectedLanguageValue"
value="{{ option.value }}"> {{ option.label | translate }}
</label>
</div>
</div>
</div>
<div class="row user-preference-block">
<table data-ng-repeat="preferenceItem in preferencesData.userNotificationPreferencesList"
class="table table-bordered table-striped user-preference-table">
<thead>
<tr>
<th>{{ preferenceItem.label | translate }}</th>
<th>{{ 'organisation.mediaPreference.selected' | translate }}?</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="mediaOption in preferenceItem.mediaOptionList">
<td class="first-column">
{{ mediaOption.label | translate}}
</td>
<td class="second-column">
<input type="checkbox"
id="inputStatus1-{{ mediaOption.id }}"
value="{{ mediaOption.id }}"
ng-checked="mediaOption.userChoice"
data-ng-click="clickHandler.checkValue(mediaOption.id)">
</td>
</tr>
</tbody>
</table>
</div>
<div class="prj-form-actions"
data-spectrum-style-affix
data-threshold="150"
data-css-class="sdx-sticky-container">
<button id="selectAllButton"
class="btn btn-default"
type="button"
data-ng-click="clickHandler.selectAll()"
data-translate="global.buttons.selectAll">
</button>
<button id="deselectAll"
class="btn btn-default"
type="button"
data-ng-click="clickHandler.deselectAll()"
data-translate="global.buttons.deselectAll">
</button>
<button id="saveBtn"
class="btn btn-default"
type="button"
data-ng-click="clickHandler.saveButton()"
data-translate="global.buttons.save">
</button>
<button id="cancelBtn"
class="btn btn-default"
type="button"
data-ng-click="clickHandler.deselectAll()"
data-translate="global.buttons.cancel">
</button>
</div>
</fieldset>
</form>
</div>
<div class="clearfix"></div>
<!-- / edit-my-account-page-view -->
controller file:
angular.module(
'EditUserPreferencesPageControllerModule',
[]
).controller(
'EditUserPreferencesPageController',
[
'$scope',
'$location',
'$routeParams',
'$filter',
'$window',
'$modal',
'PageTitleModel',
'SpectrumPageHeaderModel',
'AccountModel',
'UserModel',
'OrganisationService',
'RolesModel',
'MediaPreferencesModel',
'UserService',
'EmailNotificationService',
'EmailNotificationModel',
'SpectrumErrorModel',
'SpectrumHATEOASHelper',
function ($scope,
$location,
$routeParams,
$filter,
$window,
$modal,
PageTitleModel,
SpectrumPageHeaderModel,
AccountModel,
UserModel,
OrganisationService,
RolesModel,
MediaPreferencesModel,
UserService,
EmailNotificationService,
EmailNotificationModel,
SpectrumErrorModel) {
var impersonateUserCode = AccountModel.account.impersonatedUserCode,
userCode = impersonateUserCode ? impersonateUserCode : $routeParams.userCode;
$scope.mediaPreferencesModel = MediaPreferencesModel;
$scope.userModel = UserModel;
$scope.emailNotificationModel = EmailNotificationModel;
$scope.rolesModel = RolesModel;
$scope.statusList = [];
$scope.relationshipNotificationList = [];
$scope.auditNotificationList = [];
$scope.testListMediaValue = [];
$scope.preferencesData = {};
$scope.pleaseSelect = $filter('translate')('global.placeholders.pleaseSelect');
function initialise() {
PageTitleModel.setTitle('user.pageTitles.emailNotification');
SpectrumPageHeaderModel.setTitle('user.pageTitles.emailNotification');
SpectrumErrorModel.clearErrorsForScope($scope.$id);
generateOptions();
loadUserData();
}
function generateOptions() {
for (var status in MediaPreferencesModel.STATUS) {
if (MediaPreferencesModel.STATUS[status].domainType === 'Relationship') {
$scope.relationshipNotificationList.push(MediaPreferencesModel.STATUS[status]);
} else if (MediaPreferencesModel.STATUS[status].domainType === 'Audit') {
$scope.auditNotificationList.push(MediaPreferencesModel.STATUS[status]);
}
}
}
function loadUserData() {
UserService.getOne(userCode).then(
function successHandler(successResponse) {
UserModel.populateFromJSON(successResponse.data);
getNotificationPreferences();
},
function errorHandler(errorResponse) {
SpectrumErrorModel.handleErrorResponse($scope.$id, errorResponse);
}
);
}
function getNotificationPreferences() {
EmailNotificationService.getNotificationPreferences(UserModel.userCode).then(
function successHandler(successResponse) {
$scope.preferencesData = successResponse.data;
EmailNotificationModel.populateData($scope.preferencesData);
},
function errorHandler(errorResponse) {
SpectrumErrorModel.handleErrorResponse($scope.$id, errorResponse);
}
);
}
function saveData() {
var a = $scope.testListMediaValue;
EmailNotificationService.saveNotificationPreferences(UserModel.userCode, EmailNotificationModel.getJsonForSavePreferences()).then(
function successHandler(successResponse) {
console.log(successResponse);
},
function errorHandler(errorResponse) {
SpectrumErrorModel.handleErrorResponse($scope.$id, errorResponse);
}
);
}
$scope.clickHandler = {
saveButton: function () {
saveData();
},
backButton: function () {
$location.path(viewUserPath());
},
selectAll: function () {
angular.forEach(MediaPreferencesModel.relationshipStatus, function (itm) {
itm.userChoice = true;
});
},
deselectAll: function () {
angular.forEach(MediaPreferencesModel.relationshipStatus, function (itm) {
itm.userChoice = false;
});
},
checkValue: function (isChecked) {
console.log(isChecked);
}
};
function viewUserPath() {
return '/user/view/' + userCode;
}
$scope.canShow = {
emailPreferences: function () {
var preferenceFields = MediaPreferencesModel.preferenceFields;
return (preferenceFields.length > 0);
},
isRelationshipNotification: function (reference) {
return reference.domainType === 'Relationship';
},
isAuditNotification: function (reference) {
return reference.domainType === 'Audit';
}
};
initialise();
}
]
);
model
angular.module(
'EmailNotificationModelModule',
[]
).factory(
'EmailNotificationModel', [
function () {
return {
selectedLanguageValue: '',
userNotificationPreferencesList: [],
getJsonForSavePreferences: function () {
var json = {};
json.selectedLanguageValue = this.selectedLanguageValue;
json.userNotificationPreferencesList = this.userNotificationPreferencesList;
return json;
},
populateData: function (preferencesData) {
this.selectedLanguageValue = preferencesData.selectedLanguage.value;
}
};
}
]
);
JSON parse when I call get function to generate form
{
selectedLanguage: {
label: 'Spain',
value: 'sp'
},
languageOptionList: [
{
label: 'English',
value: 'en'
},
{
label: 'Chinese',
value: 'cn'
},
{
label: 'Spain',
value: 'sp'
},
{
label: 'French',
value: 'fr'
},
{
label: 'Portuguese',
value: 'po'
},
{
label: 'Japanese',
value: 'jp'
}
],
userNotificationPreferencesList: [
{
label: 'organisation.mediaPreference.tradingRelationships',
domainType: 'tradingRelationShip',
mediaOptionList: [
{
id: 'ACCEPTED',
label: 'organisation.relationshipStatuses.accepted',
order: 1,
userChoice: true
},
{
id: 'INITIATED',
label: 'organisation.relationshipStatuses.initiated',
order: 2,
userChoice: false
},
{
id: 'REJECTED',
label: 'organisation.relationshipStatuses.rejected',
order: 3,
userChoice: true
}
]
},
{
label: 'organisation.mediaPreference.auditNotifications',
domainType: 'auditNotification',
mediaOptionList: [
{
id: 'AUDIT_CREATED',
label: 'organisation.auditStatuses.created',
order: 4,
userChoice: true
},
{
id: 'AUDIT_ACCEPTED',
label: 'organisation.auditStatuses.accepted',
order: 5,
userChoice: false
}
]
}
]
};
The correct way to use NgModel with input[checkbox] can be found here.
For your implementation, change this
<input type="checkbox"
id="inputStatus1-{{ mediaOption.id }}"
value="{{ mediaOption.id }}"
ng-checked="mediaOption.userChoice"
data-ng-click="clickHandler.checkValue(mediaOption.id)">
To this
<input type="checkbox"
ng-model="mediaOption.userChoice"
ng-change="clickHandler.checkValue(mediaOption.id)">
I am very new to Angular JS and Ionic framework .
In services.js file, inside .factory method ,the webservice is invoked and can show the alert with the json response as shown in the screenshot below
But, the list view is not populated. I have tried in the two ways .
Try 01:
Angular JS code
angular.module('starter.services', [])
.factory('Chats', function($http) {
var chats;
return {
all: function() {
$http.get(url).
then(function(response) {
//alert(JSON.stringify(response.data.employee));
chats=response.data.employee;
alert(JSON.stringify(chats));
return chats;
}, function(error) {
alert(JSON.stringify(error));
});
return chats;
}
};
});
HTML5 code
<ion-view view-title="Chats">
<ion-content>
<ion-list>
<ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap">
<img ng-src="http://findicons.com/files/icons/820/simply_google/256/google_android.png">
<h2>{{chat.employeeCode}}</h2>
<p>{{chat.createdBy}}</p>
<i class="icon ion-chevron-right icon-accessory"></i>
<ion-option-button class="button-assertive" ng-click="remove(chat)">
Delete
</ion-option-button>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
Try 2
In this try I have assigned the chats variable in the same file to the following array,
var chats = [{
id: 0,
name: 'Ben Sparrow',
lastText: 'You on your way?',
face: 'https://pbs.twimg.com/profile_images/514549811765211136/9SgAuHeY.png'
}, {
id: 1,
name: 'Max Lynx',
lastText: 'Hey, it\'s me',
face: 'https://avatars3.githubusercontent.com/u/11214?v=3&s=460'
}, {
id: 2,
name: 'Adam Bradleyson',
lastText: 'I should buy a boat',
face: 'https://pbs.twimg.com/profile_images/479090794058379264/84TKj_qa.jpeg'
}, {
id: 3,
name: 'Perry Governor',
lastText: 'Look at my mukluks!',
face: 'https://pbs.twimg.com/profile_images/598205061232103424/3j5HUXMY.png'
}, {
id: 4,
name: 'Mike Harrington',
lastText: 'This is wicked good ice cream.',
face: 'https://pbs.twimg.com/profile_images/578237281384841216/R3ae1n61.png'
}];
var chats = [{
id: 0,
name: 'Ben Sparrow',
lastText: 'You on your way?',
face: 'https://pbs.twimg.com/profile_images/514549811765211136/9SgAuHeY.png'
}, {
id: 1,
name: 'Max Lynx',
lastText: 'Hey, it\'s me',
face: 'https://avatars3.githubusercontent.com/u/11214?v=3&s=460'
}, {
id: 2,
name: 'Adam Bradleyson',
lastText: 'I should buy a boat',
face: 'https://pbs.twimg.com/profile_images/479090794058379264/84TKj_qa.jpeg'
}, {
id: 3,
name: 'Perry Governor',
lastText: 'Look at my mukluks!',
face: 'https://pbs.twimg.com/profile_images/598205061232103424/3j5HUXMY.png'
}, {
id: 4,
name: 'Mike Harrington',
lastText: 'This is wicked good ice cream.',
face: 'https://pbs.twimg.com/profile_images/578237281384841216/R3ae1n61.png'
}];
HTML5
<ion-view view-title="Chats">
<ion-content>
<ion-list>
<ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap">
<img ng-src="https://pbs.twimg.com/profile_images/514549811765211136/9SgAuHeY.png">
<h2>{{chat.name}}</h2>
<p>{{chat.lastText}}</p>
<i class="icon ion-chevron-right icon-accessory"></i>
<ion-option-button class="button-assertive" ng-click="remove(chat)">
Delete
</ion-option-button>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
Try 2 is working as well as I have assigned hardcoded json array to the variable . But, Try 1 is not working .
UPDATE:
controller.js
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope) {})
.controller('ChatsCtrl', function($scope, Chats) {
$scope.chats = Chats.all();
})
/*.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
})*/
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
Please help me finding the solution .
You're not waiting for the promise to resolve in your controller.
Change your controller call of Chats.all() to:
Chats.all().then(function(chats) {
$scope.chats = chats;
});
Also, change the all function in your service to:
function all() {
return $http
.get(url)
.then(function(response) {
chats = response.data.employee;
return chats;
}, function(error) {
alert(JSON.stringify(error));
});
}
I'm having trouble rendering dynamic checkboxes with JSON API response.
This 2 ng-repeats:
Bringing the listing of categories in BD, and;
ng-model with the selected category listing.
Below my HTML code;
<ul class="list-group">
<li class="list-group-item" ng-repeat="cats in categorias">
<div class="checkbox"><label><input type="checkbox" ng-model="checkbox[item.cats]"><span class="checkbox-material"><span class="check"></span></span></label> {{cats.name}}</div>
</li>
</ul>
JSON/API response (1)
[
{"id":"1","id_module":"1","name":"Esportes"},
{"id":"2","id_module":"1","name":"Entretenimento"},
{"id":"3","id_module":"1","name":"Terror"},
{"id":"4","id_module":"1","name":"Drama"}
]
JSON response (2)
{cats":["1","2"]}
I would like that the checkbox stay checked with the response.
Does anyone have any idea?
Here you have working fiddle, check it
jsfiddle.net/b895j3ay
var app = angular.module("Application", [])
app.controller('Ctrl', function($scope) {
$scope.roles = [{
id: 1,
text: 'guest'
}, {
id: 2,
text: 'user'
}, {
id: 3,
text: 'customer'
}, {
id: 4,
text: 'admin'
}];
$scope.isChecked = function(id, matches) {
var isChecked = false;
angular.forEach(matches, function(match) {
if (match === id) {
isChecked = true;
}
});
return isChecked;
}
$scope.user = {
roles: [2, 4, 3]
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<div ng-app="Application">
<div ng-controller="Ctrl">
<label ng-repeat="role in roles">
<input type="checkbox" ng-model="user.roles" checklist-value="role.id" ng-checked="isChecked(role.id,user.roles)">{{role.text}}
</label>
</div>
</div>
</div>
I've a search box and multiple categories links available in the HTML page.
as soon as user input in searchBox, i want to show:
p in Products | filter {serachedText}
When user clicks a category hyperlink, i want to show
p in Products | filter {categoryID}
But because serachedText is still avialble, result showing for
p in Products | filter {categoryID} | filter {serachedText}
Is there any way i can clear the serachedText as soon as user clicks on anylink.
That would be really easy to do in angularjs.
In html.
<input ng-model="mytext">
<a href ng-click="mytext=''">Clear Text</a>
jsfiddle is here.
Your filter expression is wrong.
if your data is a JSON array having category and name properties like so:
self.Products = [
{ category: 1, name: 'Pencil' },
{ category: 1, name: 'Notebook' },
{ category: 2, name: 'Kitten' }
];
And you are binding the following things for the selected category and search text:
self.category = 1;
self.searchText = 'pen';
You could create a complex filter expression like so:
filter: { category: vm.category | name: vm.searchText }
This will filter both on category and searchText or in combination.
To clear out the searchText, you can watch if category changes using $scope.$watch and when it changes, clear up the searchText.
Take a look at the example below or at http://plnkr.co/edit/OEDvOn. In the example, my filter expression is a bit more complicated since the selected category is actually an object containing value and name properties for the selected category, thus I need to add .value to get the right thing to pass to the filter.
Another point: For doing client side filtering, this is fine, but if you are filtering on server side, I'd rather get the filtering done on a service layer and just returned the filtered result instead of all possible data... save bandwidth and transfer time.
(function(undefined) {
'use strict';
angular.module('myApp',[]);
angular.module('myApp')
.controller('searchCtrl', searchCtrl);
searchCtrl.$inject = ['$log', '$scope'];
function searchCtrl($log, $scope) {
/* jshint validthis: true */
var self = this;
self.searchText = undefined;
self.categories = [
{ value: undefined, name: 'All' },
{ value: 1, name: 'Fruit' },
{ value: 2, name: 'Snacks' },
{ value: 3, name: 'Flower' },
{ value: 4, name: 'Pet' },
{ value: 5, name: 'Stationary' }
];
self.category = self.categories[0];
self.data = [
{ category: 1, name: 'Apple' },
{ category: 1, name: 'Grapes' },
{ category: 2, name: 'Dorito' },
{ category: 2, name: 'KitKat' },
{ category: 3, name: 'Roses' },
{ category: 3, name: 'Orchid' },
{ category: 4, name: 'Hamster' },
{ category: 4, name: 'Kitten' },
{ category: 5, name: 'Pencil' },
{ category: 5, name: 'Notebook' }
];
$scope.$watch(function() { return self.category; }, function(val, old) {
self.searchText = undefined;
});
}
}());
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="myApp" ng-controller="searchCtrl as vm">
<div class="form-group">
<label>Category</label>
<select class="form-control" ng-options="cat.name for cat in vm.categories" ng-model="vm.category">
</select>
</div>
<div class="input-group">
<input class="form-control" type="textbox" ng-model="vm.searchText" placeholder="Search text here..." />
<span class="input-group-btn">
<button type="button" class="btn btn-primary">
<i class="glyphicon glyphicon-search"></i> Search</button>
</span>
</div>
<div class="well well-sm" style="margin-top:20px">
<ul ng-repeat="item in vm.data | filter:{category:vm.category.value, name:vm.searchText}">
<li>{{item.name}}</li>
</ul>
</div>
</div>
I'd suggest directive will be the best option
MarkUp
<input ng-model="mytext">
<a href ng-click="mytext=''" clear="mytext">Clear Text</a>
Directive
app.directive('a', function() {
return {
restrict: 'E',
scope: {
clear: '='
},
compile: function(scope, ele, attrs) {
ele.on('click', function() {
scope.$apply(function() {
scope.clear = undefined;
})
})
}
}
})