bind data in $ionicPopup - angularjs

when i click on qty than it will be set on ionicPopup
$ionicPopup.show({
template: '<input type="tel" placeholder="Quantity" ng-model="data.wifi" >',
title: 'Enter quantity to change',
scope: $scope,
buttons: [{
text: '<i class="icon ion-close"></i>', type: 'popup-close'},
{
text: '<b>Ok</b>',
type: 'common-btn',
onTap: function (e) {
qty = $scope.data.wifi;
var date = new Date();
var cartData = {
'companyId': compid,
'userId': userid,
'cartDate': date,
'cartStatus': 1,
'productId': val.ProductID,
'quantity': qty,
'cartDetailStatus': 1
};
//alert(JSON.stringify(cartData));
$http.post($rootScope.url + 'UpdateCartQty?margin=' + marginVal + '&roleid=' + roleid, cartData).success(function (data) {
console.log(JSON.stringify(data));
$ionicPopup.alert({
title: 'Message',
template: 'Quantity updated successfully !'
}).then(function () {
$scope.items = data;
//cartid = data.CartID;
});
});
return qty;
}]
}).then(function (qty) {
if (qty) {
console.log('Got quantity ' + qty);
} else {
//alert('please enter value');
}
}
});
I want to bind quantity from my database value so how can not bind the value in ionic popup it's possible in ionicPopup? any help thanks in advance

You can do it. This is the content of your controller:
var compid = 1;
var userid = 1;
var val = {
ProductID: 1
};
$scope.data = {
wifi: "my wifi data"
};
$scope.openModal = function(){
$ionicPopup.show({
template: '<input type="tel" placeholder="Quantity" ng-model="data.wifi" >',
title: 'Enter quantity to change',
scope: $scope,
buttons: [
{
text: '<i class="icon ion-close"></i>',
type: 'popup-close'
},
{
text: '<b>Ok</b>',
type: 'common-btn',
onTap: function (e) {
qty = $scope.data.wifi;
var date = new Date();
var cartData = {
'companyId': compid,
'userId': userid,
'cartDate': date,
'cartStatus': 1,
'productId': val.ProductID,
'quantity': qty,
'cartDetailStatus': 1
};
//alert(JSON.stringify(cartData));
$http.post($rootScope.url + 'UpdateCartQty?margin=' + marginVal + '&roleid=' + roleid, cartData).success(function (data) {
console.log(JSON.stringify(data));
$ionicPopup.alert({
title: 'Message',
template: 'Quantity updated successfully !'
}).then(function () {
$scope.items = data;
//cartid = data.CartID;
});
});
return qty;
}
}
]
}).then(function (qty) {
if (qty) {
console.log('Got quantity ' + qty);
} else {
//alert('please enter value');
}
});
};
This is the template:
<ion-view view-title="My View">
<ion-content class="padding">
<input type="text" ng-model="data.wifi">
<button class="button" ng-click="openModal()">Open</button>
</ion-content>
</ion-view>

Related

how to add localization in ionic popup

i had completed ionic project. i would like to change lanaguages in this code. project title, place holder , button it had changed but popup was doesn't changed. i used this code in controller and language change file.
farmer-ctrl.js :
function showPopup () {
$scope.data = {};
var myPopup = $ionicPopup.show({
template: '<input type="text" ng-model="data.category">',
title: '{{"farmers_message" | translate}}', //'Enter CoconutType',
scope: $scope,
buttons: [
{ text: 'Cancel' },
{
text: '<b>{{"save_message" | translate}}</b>',
type: 'button-positive',
onTap: function (e) {
if (!$scope.data.category) {
//don't allow the user to close unless he enters producttype
e.preventDefault();
} else {
$log.log('yes clicked: ', $scope.data.category);
addProductType();
return $scope.data.category;
}
}
},
]
});
myPopup.then(function (res) {
$log.log('Tapped!', res);
});
}
i had founded by adding translate.instant
function showPopup () {
$scope.data = {};
var myPopup = $ionicPopup.show({
template: '<input type="text" ng-model="data.category">',
// title: 'Enter CoconutType',
title: $translate.instant('{{"farmers_message" | translate}}'),
scope: $scope,
buttons: [
{ text: 'Cancel' },
{
text: $translate.instant('{{"save_message" | translate}}'),
type: 'button-positive',
onTap: function (e) {
if (!$scope.data.category) {
//don't allow the user to close unless he enters producttype
e.preventDefault();
} else {
$log.log('yes clicked: ', $scope.data.category);
addProductType();
return $scope.data.category;
}
}
},
]
});
myPopup.then(function (res) {
$log.log('Tapped!', res);
});
}
To add localization in popup you need something like this:
var alertPopup = $ionicPopup.alert({
title: $translate.instant('networkerror'),
template: '<div><p translate="onlinemessagepois"></p></div>'
});
where networkerror and onlinemessagepois exist in your local js files. (Example: "networkerror":"sometext","onlinemessagepois":"someothertext" )
Note: you have to inject $translate in your controller.

$scope on $ionicPopup not recognized

I need a dynamic popup where images change its opacity when clicked. It works perfectly, but only when the popup is out of a function. I need it inside a function.
This is my controller:
$scope.imgIds = ['0', '1', '2', '3', '4', '5'];
$scope.selectedImg = '-1';
$scope.itemClicked = function(index){
console.log(index);
$scope.selectedImg = index;
}
/*$ionicPopup.prompt({
title: 'Como foi seu treino?',
scope: $scope,
templateUrl: 'templates/icons.html'
});*/
//Envia Mensagem do Treino
$scope.sendMessage = function(tempo,id_serie) {
$ionicPopup.prompt({
title: 'Como foi seu treino?',
scope: $scope,
templateUrl: 'templates/icons.html'
}).then(function(res) {
$http({
url: $localStorage.url+'/serie/mensagem',
method: 'POST',
data: {id_serie : id_serie, mensagem :res, tempo: tempo, datahora: $scope.getData()},
headers : {'Content-Type':'application/json; charset=UTF-8'}
});
});
}
//Finaliza Treino
$scope.finalizar = function() {
document.getElementById('timer').getElementsByTagName('timer')[0].stop();
document.getElementById('play').className = 'button icon button-balanced button-block ion-play col';
var tempo = document.getElementById('timer').getElementsByTagName('timer')[0].innerText;
var confirmPopup = $ionicPopup.confirm({
title: 'Atenção',
template: 'Tempo: '+tempo+'<br>Finalizar Treino?',
buttons: [
{ text: 'Cancelar', onTap: function(e) { return false; }},
{ text: '<b>Ok</b>',
type: 'button-positive',
onTap: function(e) {
document.getElementById('timer').getElementsByTagName('timer')[0].start();
document.getElementById('timer').getElementsByTagName('timer')[0].stop();
$state.go('tab.series', {});
$scope.sendMessage(tempo,$scope.id_serie);
}
},
]
});
}
This is icons.html:
<style>
.selected {opacity:1;margin:auto;}
.unselected {opacity:0.5;margin:auto;}
</style>
<div class='row'>
<img ng-repeat="imgId in imgIds" src="img/{{imgId}}.png" width="30" height="30"
ng-class="{'selected':{{imgId}}==selectedImg,'unselected':{{imgId}}!=selectedImg}" ng-click="itemClicked(imgId)"/>
</div>
Algum Comentário?<br>
<input type="text"/>
There is no error on console. But the images don't change css, the popup gets locked and the buttons doesn't do nothing.
I got it.
The problem is I put $state.go('tab.series'); before call the popup, so the scope were different.

Reload controller with $http.get after $http.post

i have problem with my IONIC app.
I want reload my data what i recieve from nodeJS by $http.get, after $http.post.
Here is my code:
.controller('todoTodayCtrl',
function($scope, AuthService, API_ENDPOINT, $http, $state, $ionicPopup) {
$http.get(API_ENDPOINT.url + '/today').then(function(result) {
$scope.todaylist = result.data.msg;
});
})
.controller('todoTodayNewCtrl',
function($scope, AuthService, API_ENDPOINT, $http, $state, $ionicPopup){
$scope.today = {
title: ''
};
$scope.todoNewButton = function() {
$http.post(API_ENDPOINT.url + '/today', $scope.today).then(function(result) {
$state.go('menu.todoToday');
}, function(errMsg) {
var alertPopup = $ionicPopup.alert({
title: 'Nelze přidat Todo',
template: errMsg
});
});
};
})
and first page
<ion-view title="Todo Today" ng-controller="todoTodayCtrl">
<ion-content overflow-scroll="true" padding="true" class="has-header">
<ion-list>
<ion-item class="item-divider" ng-repeat="today in todaylist">{{today.title}} - {{today.time}}</ion-item>
<button class="button button-stable button-block " ui-sref="menu.todoTodayNew">Přidat todo</button>
</ion-list>
</ion-content>
and page with form
<ion-view title="Nové todo today">
<ion-content overflow-scroll="true" padding="true" class="has-header">
<ion-list>
<label class="item item-input">
<span class="input-label">Nový úkol</span>
<input type="text" placeholder="Nová položka" ng-model="today.title">
</label>
<button class="button button-stable button-block " ng-click="todoNewButton()">Přidat todo today</button>
</ion-list>
</ion-content>
You have to push the new today value in your $scope.todaylist in your POST request callback:
$http.post(API_ENDPOINT.url + '/today', $scope.today).then(function(result) {
$scope.todaylist.push(result);
$state.go('menu.todoToday');
}, function(errMsg) {
var alertPopup = $ionicPopup.alert({
title: 'Nelze přidat Todo',
template: errMsg
});
});
Or pass the result to your todoTodayCtl via $state.
$state.go('menu.todoToday', {myParam: {some: 'thing'}})
$stateProvider.state('menu.todoToday', {
url: '/myState',
params: {myParam: null}, ...
and then access the parameter in your controller.
$stateParams.myParam //should be {some: 'thing'}
And my server NodeJs
apiRoutes.post('/today', passport.authenticate('jwt', {session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
console.log(req.body.title);
var newToday = new Today({
title: req.body.title,
time: 'Timeee',
user: user.name
});
newToday.save(function(err) {
if (err) {
res.json({succes: false, msg: 'Error'});
} else {
res.status(200).json({succes: true, msg: newToday});
}
});
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
Solved
.controller('todoTodayCtrl', function($scope, $rootScope, AuthService, API_ENDPOINT, $http, $state, $ionicPopup) {
$rootScope.todaylist = [];
$http.get(API_ENDPOINT.url + '/today').then(function(result) {
$rootScope.todaylist = result.data.msg;
});
})
.controller('todoTodayNewCtrl', function($scope, $rootScope, AuthService, API_ENDPOINT, $http, $state, $ionicPopup){
$scope.today = {
title: '',
time: ''
};
$scope.todoNewButton = function() {
$http.post(API_ENDPOINT.url + '/today', $scope.today).then(function(result) {
$rootScope.todaylist.push(result.data.msg);
$state.go('menu.todoToday');
}, function(errMsg) {
var alertPopup = $ionicPopup.alert({
title: 'Nelze přidat Todo',
template: errMsg
});
});
};
})

use column in angularjs uigrid

I am using angularjs uigrid with $scope http to get data from controller.
now here i used columns like this:
<div ng-app = "myapp" ng-controller="HelloController">
<div id="grid1" ui-grid="{ data: myData }" class="grid"></div>
</div>
<script type="text/javascript">
var StudentApp = angular.module('myapp', ['ui.grid']);
StudentApp.controller('HelloController', function ($scope, StudentService) {
$scope.columnDefs = [
{ field: 'FirstName', title: 'fname' },
{ field: 'Last Name' },
{ field: 'Salary' },
{ field: 'DOB' }
],
getStudents();
function getStudents() {
StudentService.getStudents()
.success(function (studs) {
$scope.myData = studs;
console.log($scope.students);
})
.error(function (error) {
$scope.status = 'Unable to load customer data: ' + error.message;
console.log($scope.status);
});
}
});
StudentApp.factory('StudentService', ['$http', function ($http) {
var StudentService = {};
StudentService.getStudents = function () {
return $http.get('/Home/GetEmployee');
};
return StudentService;
} ]);
</script>
in this i have used $scope.columndefs but it is not working.
And how to format date value here?
When i run this apps value is showing in below like after some 30 lines value is showing.
Try this
<div ng-app = "myapp" ng-controller="HelloController">
<div id="grid1" ui-grid="gridoptions" class="grid"></div>
</div>
<script type="text/javascript">
var StudentApp = angular.module('myapp', ['ui.grid']);
StudentApp.controller('HelloController', function ($scope, StudentService) {
$scope.columnDefs = [
{ field: 'FirstName', title: 'fname' },
{ field: 'Last Name' },
{ field: 'Salary' },
{ field: 'DOB' }
],
$scope.gridoptions = {
data:'myData',
columnDefs: $scope.columnDefs,
}
getStudents();
function getStudents() {
StudentService.getStudents()
.success(function (studs) {
$scope.myData = studs;
console.log($scope.students);
})
.error(function (error) {
$scope.status = 'Unable to load customer data: ' + error.message;
console.log($scope.status);
});
}
});
StudentApp.factory('StudentService', ['$http', function ($http) {
var StudentService = {};
StudentService.getStudents = function () {
return $http.get('/Home/GetEmployee');
};
return StudentService;
} ]);
</script>
I hope this would work.

Angular UI Bootstrap modal result is undefined

I'm building an app that loads a modal on a click on a button in an ng-grid row. Displaying the modal and the correct data works great. Problem is with getting the data back form the form in the modal. This bit of code
modalInstance.result.then(function(selectedItem){
$scope.selected = selectedItem;
});
Returns 'undefined' for 'selectedItem'
Here's the modal.
<div ng-app="myApp">
<div ng-controller="UsersCtrl">
<script type="text/ng-template" id="editUserModal.html">
<div class="modal-header">
<h3 class="modal-title">Edit User <em>{{user.user_full_nm}} {{user.user_id}}</em></h3>
</div>
<div class="modal-body">
<p>User Name: <input type="text" name="user_full_nm" value="{{user.user_full_nm}}"></p>
<p>Email: <input type="text" name="user_nm" value="{{user.user_nm}}"></p>
<p>Active:
<select ng-model="user.deleted" ng-selected="user.deleted">
<option value="0" ng-selecte>Active</option>
<option value="1">Inactive</option>
</select>
</p>
<p>Termination Date: {{user.termination_date | date:'longDate'}}</p>
<p>Last Entry Date: {{user.last_entry | date:'longDate'}}</p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
<div class="gridStyle" ng-grid="gridOptions"></div>
</div>
</div>
Here's the Angular app.
var app = angular.module('myApp', ['ngGrid','ui.bootstrap']);
app.controller('UsersCtrl', function($scope, $http, $modal) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: false
};
$scope.totalServerItems = 0;
$scope.pagingOptions = {
pageSizes: [20, 40, 60],
pageSize: 20,
currentPage: 1
};
$scope.setPagingData = function(data, page, pageSize){
var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
$scope.userData = pagedData;
$scope.totalServerItems = data.length;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
setTimeout(function () {
var data;
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('getUsers').success(function (largeLoad) {
data = largeLoad.filter(function(item) {
return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
});
$scope.setPagingData(data,page,pageSize);
});
} else {
$http.get('getUsers').success(function (largeLoad) {
$scope.setPagingData(largeLoad,page,pageSize);
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize,$scope.pagingOptions.currentPage,$scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage,
$scope.filterOptions.filterText);
}
}, true);
var editUserButtonTemplate = '<i class="fa fa-pencil" style="cursor:pointer;" ng-click="editUser(row.entity)"></i>';
$scope.gridOptions = {
data: 'userData',
columnDefs: [
{field: 'user_id', displayName: 'User ID', visible: false},
{field: 'user_nm', displayName: 'Email'},
{field: 'user_full_nm', displayName: 'Name'},
{field: 'deleted', displayName: 'Active', width: 60, cellFilter: 'activeFilter'},
{field: 'termination_date', displayName: 'Termination Date',cellFilter: 'date:\'longDate\''},
{field: 'last_entry', displayName: 'Last Entry Date',cellFilter: 'date:\'longDate\''},
{field: '', DisplayName: '', cellTemplate: editUserButtonTemplate, colFilterText: '', width:20}
],
enablePaging: true,
showFooter: true,
showFilter: true,
enableRowSelection: false,
filterOptions: $scope.filterOptions,
totalServerItems:'totalServerItems',
pagingOptions: $scope.pagingOptions,
filterOptions: $scope.filterOptions
};
/************ open the edit user modal *********************/
$scope.editUser = function(value) {
var modalInstance = $modal.open({
templateUrl: 'editUserModal.html',
// scope: $scope,
controller: 'editUserCtrl',
resolve: {
user: function () {
return value;
}
}
});
modalInstance.result.then(function(selectedItem){
$scope.selected = selectedItem;
});
};
});
app.controller('editUserCtrl', function($scope, $http, $modalInstance, user) {
$scope.user = user;
$scope.ok = function () {
$modalInstance.close($scope.selected);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
// for the 'deleted' column, display 'Active' or 'Inactive' instead of 1 or 0
app.filter('activeFilter', function(){
var types = ['Active', 'Inactive'];
return function(type){
return types[type];
};
});
So as happens so often, as soon as I posted my question I found this one.
angular-ui-bootstrap modal not passing back result
Which led me to the problem.
$scope.ok = function () {
$modalInstance.close($scope.selected);
};
Changed $scope.selected to $scope.user and it's working as expected now.

Resources