$scope is not binding data in view - angularjs

I've been developing an e-commerce website and I am stuck at a point. I am using Stripe payment and all is working fine except data biding after token creation. Here is my controller
app.controller('shoppingCartController', ['$scope', '$http', '$sce', 'stripe', '$window', function ($scope, $http, $sce, stripe, $window) {
$window.Stripe.setPublishableKey('pk_test_saiYYlyCNgO2yZq6Mu******');
$scope.createToken = function () {
var expire = $scope.master[0].expire.split('/');
if ($scope.userDetail.$valid === true) {
$window.Stripe.card.createToken({
number: $scope.master[0].card,
cvc: $scope.master[0].cvv,
exp_month: expire[0],
exp_year: expire[1],
}, $scope.makepayment);
}
}
$scope.makepayment = function (status, response) {
if (response.error) {
$scope.handleStripeCallback(response);
} else {
// response contains id and card, which contains additional card details
var data = {token: response.id, data: $scope.cartData};
$http.post('make_payment', data).success(function (data) {
if (data.status) {
$scope.stripePaymentMessage = data.message;
$scope.stripePaymentMessageClass = "success";
} else {
$scope.stripePaymentMessage = data.message;
$scope.stripePaymentMessageClass = "danger";
}
})
}
}
$scope.handleStripeCallback = function (response) {
//alert(response.error.message);
$scope.stripChargeRequest = true;
$scope.stripePaymentMessage = response.error.message;
$scope.stripePaymentMessageClass = "danger";
}
}]);
In my view I am trying to handle error or success message with this code
<div ng-show="stripChargeRequest ">
<div class="alert alert-{{stripePaymentMessageClass}}" role="alert" >
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
{{stripePaymentMessage}}
</div>
</div>
My question is: stripChargeRequest angular variable contain true / false with normal scope binding but when I am trying to create a token by calling $scope.createToken() it not works. I guess I am forgetting something in calling callback function $scope.makepayment(). Fortunately it is working in controller's scope. I can see error after stripe request in controller but it is not showing in view. Please suggest me the proper way of doing that. Thanks in advance.

The stripe callbacks are outside of angular so you need to use $apply to tell angular whenever you update the scope so it can run a digest to update the view
Example:
$scope.handleStripeCallback = function (response) {
//alert(response.error.message);
$scope.stripChargeRequest = true;
$scope.stripePaymentMessage = response.error.message;
$scope.stripePaymentMessageClass = "danger";
$scope.$apply(); // tell angular to update view
}

Related

Angular modal service closing issue

I am using angular modal service to show incoming call popup.
Everything seems to work but in particular case the popup closes leaving behind grey overlay blocking the whole UI.
Popup closes perfectly when i manually click reject and close button provided in popup but gives unusual behaviour when i use timeout to close the popup whithout doing any operation on it.
For reference i am giving my whole code.
----------------------------modal popup UI code---------------------------
<div class="modal fade">
<div class="modal-dialog modal-lg modal-dialog-custom">
<div class="modal-content modal-content-dialog">
<div class="modal-header">
<audio class="incoming-videoconference-audio" autoplay loop>
<source src="../images/dataCallIncoming.mp3" type="audio/mpeg">
</audio>
<button type="button" class="close" ng-click="vm.hangUp()" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Incoming Call</h4>
</div>
<img class="incoming-nowConf-logo" src="../images/new_nowconfer_e.png" />
<div id="state" class="grid_4 alpha">
<div class="gps_ring"></div>
</div>
<div class="modal-body modal-body-custom">
<div style="text-overflow:ellipsis;overflow:hidden;" class="call-from">
{{vm.confName}}
</div>
<div class="call-control">
<button type="button"class="btn-sm btn-sm-gray cancel-btn" ng-click="vm.hangUp()" data-dismiss="modal">Reject</button>
<span style="width:50px;"> </span>
<button type="button"class="btn-sm btn-sm-green" ng-click="vm.accept()" data-dismiss="modal">Answer</button>
</div>
</div>
</div>
</div>
</div>
-------------------------modal popup controller------------------------------
(function () {
'use strict';
angular
.module('incomingModule')
.controller('IncomingCallController', IncomingCallController);
IncomingCallController.$inject = ['$scope','$rootScope','plivoclient','$routeParams','$location','close','from', 'instId','confName','$timeout'];
function IncomingCallController($scope,$rootScope , plivoclient,$routeParams ,$location,close, from, instId,confName,$timeout) {
var vm = this;
vm.connecting = false;
vm.from = from;
vm.confName = confName;
vm.dismissModal = function(result) {
plivoclient.conn.reject();
console.log('vm.dismissModal::'+result);
close(result, 200); // close, but give 200ms for bootstrap to animate
};
activate();
function activate(){
$timeout(function(){
vm.dismissModal('cancel');
},25000);
}
vm.accept = function() {
plivoclient.conn.answer();
vm.connecting = true;
console.log("incoming call accept............");
vm.dismissModal('accept');
$timeout(function(){
$location.path( "/call/"+$rootScope.id2);
},300);
};
vm.hangUp = function() {
plivoclient.conn.reject();
vm.dismissModal('reject');
console.log("incoming call hangedup............");
};
}
}());
-------------------------opening modal code----------------------------------------
ModalService.showModal({
templateUrl: '../../partials/calls.incoming.popup.html',
controller: 'IncomingCallController',
controllerAs: 'vm',
inputs: {
from: dataNew.callerName || '',
instId: dataNew.extraHeaders['X-Ph-Instid'] || dataNew.extraHeaders['X-Ph-instid'],
confName:$rootScope.conferenceData.conf_name
}
}).then(function(modal) {
modal.element.modal();
modal.close.then(function(result) {
//$scope.message = result ? "You said Yes" : "You said No";
});
});
----------------------------------angular modal service code----------------------------------
'use strict';
let module = angular.module('angularModalService', []);
module.factory('ModalService', ['$animate', '$document', '$compile', '$controller', '$http', '$rootScope', '$q', '$templateRequest', '$timeout',
function($animate, $document, $compile, $controller, $http, $rootScope, $q, $templateRequest, $timeout) {
function ModalService() {
var self = this;
// Returns a promise which gets the template, either
// from the template parameter or via a request to the
// template url parameter.
var getTemplate = function(template, templateUrl) {
var deferred = $q.defer();
if (template) {
deferred.resolve(template);
} else if (templateUrl) {
$templateRequest(templateUrl, true)
.then(function(template) {
deferred.resolve(template);
}, function(error) {
deferred.reject(error);
});
} else {
deferred.reject("No template or templateUrl has been specified.");
}
return deferred.promise;
};
// Adds an element to the DOM as the last child of its container
// like append, but uses $animate to handle animations. Returns a
// promise that is resolved once all animation is complete.
var appendChild = function(parent, child) {
var children = parent.children();
if (children.length > 0) {
return $animate.enter(child, parent, children[children.length - 1]);
}
return $animate.enter(child, parent);
};
self.showModal = function(options) {
// Get the body of the document, we'll add the modal to this.
var body = angular.element($document[0].body);
// Create a deferred we'll resolve when the modal is ready.
var deferred = $q.defer();
// Validate the input parameters.
var controllerName = options.controller;
if (!controllerName) {
deferred.reject("No controller has been specified.");
return deferred.promise;
}
// Get the actual html of the template.
getTemplate(options.template, options.templateUrl)
.then(function(template) {
// Create a new scope for the modal.
var modalScope = (options.scope || $rootScope).$new();
var rootScopeOnClose = $rootScope.$on('$locationChangeSuccess', cleanUpClose);
// Create the inputs object to the controller - this will include
// the scope, as well as all inputs provided.
// We will also create a deferred that is resolved with a provided
// close function. The controller can then call 'close(result)'.
// The controller can also provide a delay for closing - this is
// helpful if there are closing animations which must finish first.
var closeDeferred = $q.defer();
var closedDeferred = $q.defer();
var inputs = {
$scope: modalScope,
close: function(result, delay) {
if (delay === undefined || delay === null) delay = 0;
$timeout(function() {
cleanUpClose(result);
}, delay);
}
};
// If we have provided any inputs, pass them to the controller.
if (options.inputs) angular.extend(inputs, options.inputs);
// Compile then link the template element, building the actual element.
// Set the $element on the inputs so that it can be injected if required.
var linkFn = $compile(template);
var modalElement = linkFn(modalScope);
inputs.$element = modalElement;
// Create the controller, explicitly specifying the scope to use.
var controllerObjBefore = modalScope[options.controllerAs];
var modalController = $controller(options.controller, inputs, false, options.controllerAs);
if (options.controllerAs && controllerObjBefore) {
angular.extend(modalController, controllerObjBefore);
}
// Finally, append the modal to the dom.
if (options.appendElement) {
// append to custom append element
appendChild(options.appendElement, modalElement);
} else {
// append to body when no custom append element is specified
appendChild(body, modalElement);
}
// We now have a modal object...
var modal = {
controller: modalController,
scope: modalScope,
element: modalElement,
close: closeDeferred.promise,
closed: closedDeferred.promise
};
// ...which is passed to the caller via the promise.
deferred.resolve(modal);
function cleanUpClose(result) {
// Resolve the 'close' promise.
closeDeferred.resolve(result);
// Let angular remove the element and wait for animations to finish.
$animate.leave(modalElement)
.then(function () {
// Resolve the 'closed' promise.
closedDeferred.resolve(result);
// We can now clean up the scope
modalScope.$destroy();
// Unless we null out all of these objects we seem to suffer
// from memory leaks, if anyone can explain why then I'd
// be very interested to know.
inputs.close = null;
deferred = null;
closeDeferred = null;
modal = null;
inputs = null;
modalElement = null;
modalScope = null;
});
// remove event watcher
rootScopeOnClose && rootScopeOnClose();
}
})
.then(null, function(error) { // 'catch' doesn't work in IE8.
deferred.reject(error);
});
return deferred.promise;
};
}
return new ModalService();
}]);
I have spent hours on internet to figure out why this is happening but failed to solve it,i feel when any click event happens then it works fine but fails to close properly when on operation is performed.Please help!!
thanks in advance
I had the same issue and it was due to a comment at the top of my HTML file. When I removed the comment, it worked fine.
I didn't get the reason of this bug though.
hope you have the same case.

Angular binding not working properly with ngInfiniteScroll

Basically I have a timeline with posts that is a $firebaseArray and any change to this array is getting binded properly. But when I want to bind any other data it only binds when ngInfiniteScroll is trying to retrieve more data from firebase, so only when I scroll down.
In the code bellow I'm calling {{getMoreDetails()}} and this data is binded when the first set of data is being retrieved with ngInfiniteScroll but as soon as it is loaded the bind breaks and only binds again when scrolling.
My concerns here are:
Was ngInfiniteScroll designed to work this way?
Is there any workaround in this scenario?
Stack:
"firebase": "2.4.2","angularfire": "~1.2.0","firebase-util": "0.2.5","ngInfiniteScroll": "1.2.2"
timeline.html
<div ng-controller="TimelineController">
<section class="entrys main-content" infinite-scroll="posts.scroll.next(3)" infinite-scroll-distance="0.3">
<div class="inner">
<div ng-repeat="post in filteredPostsResults = (posts | filter:postIdFilter)">
<article class="entry">
<img ng-if="post.sourceType=='IMAGE'" data-ng-src="{{getPostData(post)}}"/>
<div class="entry-info">
<h3><div ng-bind-html="post.description | emoticons"></div></h3>
<small>posted on <time>{{getDateInFormat(post.createdAt)}}</time></small>
{{getMoreDetails()}}
</div>
</article>
</div>
</div>
</section>
</div>
timeline.js
(function (angular) {
"use strict";
var timeline = angular.module('myApp.user.timeline', ['firebase', 'firebase.utils', 'firebase.auth', 'ngRoute', 'myApp.user.timelineService']);
timeline.controller('TimelineController', [ '$scope', '$routeParams', 'TimelineService', '$publisherServices', '$securityProperties', function ($scope, $routeParams, TimelineService, $publisherServices, $securityProperties) {
if (!$scope.posts){
$scope.posts = TimelineService.getPosts($routeParams.userId);
}
$scope.posts.$loaded(function(result) {
$scope.isPostsLoaded = true;
});
$scope.getMoreDetails = function() {
console.log("LOGGED ONLY WHEN SCROLLING");
return $publisherServices.getDetails();
};
$scope.getPostData = function(post) {
if (!post.dataUrl){
post.dataUrl = $publisherServices.getAwsFileUrl(post.fileName);
}
return post.dataUrl;
};
$scope.postIdFilter = function(post) {
if ($routeParams.postId){
if (post.$id == $routeParams.postId) return post;
} else { return post; }
};
$scope.getDateInFormat = function(timestamp){
var date = new Date();
date.setTime(timestamp);
return date;
};
}]);
})(angular);
timelineService.js
(function (angular) {
"use strict";
var timelineService = angular.module('myApp.user.timelineService', []);
timelineService.service('TimelineService', ['$routeParams', 'FBURL', '$firebaseArray', function ($routeParams, FBURL, $firebaseArray) {
var posts;
var currentUserIdPosts;
var postsRef;
var self = {
getPosts: function(userId){
if (!posts || userId != currentUserIdPosts){
currentUserIdPosts = userId;
postsRef = new Firebase(FBURL).child("posts").child(userId);
var scrollRef = new Firebase.util.Scroll(postsRef, "createdAtDesc");
posts = $firebaseArray(scrollRef);
posts.scroll = scrollRef.scroll;
}
return posts;
}
}
return self;
}]);
})(angular);
I am assuming that you want the post details updated when the data from your Firebase changes.
When Firebase changes are applied to your scope, it seems that it doesn't trigger a digest cycle, so you probably need to do it manually every time you get updates from Firebase.
Take a look at $$updated in $firebaseArray.$extend (see docs).
// now let's create a synchronized array factory that uses our Widget
app.factory("WidgetFactory", function($firebaseArray, Widget) {
return $firebaseArray.$extend({
// override the update behavior to call Widget.update()
$$updated: function(snap) {
// we need to return true/false here or $watch listeners will not get triggered
// luckily, our Widget.prototype.update() method already returns a boolean if
// anything has changed
return this.$getRecord(snap.key()).update(snap);
}
});
});
I hope this helps.

Initialise AngularJS service - factory on the document load

Sorry for a very stupid question but I just started working with AngularJS and OnsenUI.
I have got a service to get a data from SQLite:
module.factory('$update', function () {
var update = {};
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM event_updates', [], function (tx, results) {
var rows = results.rows;
update.items = [];
if (!rows.length) {} else {
for (var index = 0; index < rows.length; index++) {
update.items.push({
"title": rows.item(index).title,
"date": rows.item(index).date,
"desc": rows.item(index).desc
});
}
}
}, function (error) {
console.log(error);
});
});
return update;
});
And a controller which is using the data:
module.controller('UpdatesController', function ($scope, $update) {
$scope.items = $update.items;
});
As soon as my page is loaded the content is not displayed and I need to click twice to call a page with the code below to see the content:
<ons-list ng-controller="UpdatesController">
<ons-list-item modifier="chevron" class="list-item-container" ng-repeat="item in items" ng-click="showUpdate($index)">
<div class="list-item-left">
</div>
<div class="list-item-right">
<div class="list-item-content">
<div class="name">{{item.title}}</div> <span class="desc">{{item.desc}}</span>
</div>
</div>
</ons-list-item>
</ons-list>
Can anybody help how can I initialise the controller as soon as page is loaded with all content. Sorry if it is a stupid question but I am really struggling. Appreciate your help a lot.
You could store the result of the request in the factory and retrieve those instead.
module.factory('$update', function () {
var update = {};
var requestValues = function(){ // store the results of the request in 'update'
// Your db.transaction function here
}
var getUpdates = function(){ // retrieve the values from 'update'
return update;
}
return{
requestValues : requestValues,
getUpdates : getUpdates
}
});
And then in you controller:
module.controller('UpdatesController', function ($scope, $update) {
$update.requestValues();
$scope.items = $update.getUpdates();
});
You could then get the values from anywhere in you solution (by using $update.getUpdates) without having to make an extra http request.

Passing data from ionic/angular modal using separate template html file

I'm developing a simple Ionic mobile app although the answer likely lies with Angular. The app is really simple, displays a list of employees with an Add button which displays a modal, lets the user enter some details, click Save and it's persists the data to a back-end Firebase store. It has 1 controller and a simple service. Initially I had the template html for the modal inside script tags inside the index.html and it all worked fine. When I decided to structure things out and put the modal template in a separate html file, suddenly the data object assigned to ng-modal via the input boxes no longer passes any data to the event handler to save the data, instead it's always undefined. Everything else works as it should, the modal displays ok, the event handlers are calling the right functions etc. The only change is moving the input template to a separate file. I know it's likely something really simple but can't for the life of me work out why and can't find any info about it anywhere else.
Template HTML file for the modal :
<ion-list>
<h1>Add Employee</h1>
<div class="list list-inset">
<ion-item>
<label class="item item-input">
<input type="text" placeholder="Employee Name" ng-model="data.employeeName">
</label>
<label class="item item-input">
<input type="text" placeholder="Employee Age" ng-model="data.employeeAge">
</label>
</ion-item>
<button class="button button-outline button-block button-balanced"
ng-click="addEmployee(true, data)">
Save & Add Another
</button>
<button class="button button-outline button-block button-positive"
ng-click="addEmployee(false, data)">
Save
</button>
<button class="button button-outline button-block button-assertive"
ng-click="closeAddModal()">
Cancel
</button>
</ion-list>
</ion-modal-view>
addEmployee event - data parameter is now always undefined. Worked fine with embedded template :
$scope.addEmployee = function(retainModal, data) {
var employee = {employeeName:data.employeeName,
employeeAge:data.employeeAge};
employeeService.saveEmployee(employee);
if (! retainModal) {
$scope.closeAddModal();
};
data.employeeName = "";
data.employeeAge = "";
};
Based on this question and other needs I create a service that can be useful.
See this post: Ionic modal service or see in operation: CodePen
(function () {
'use strict';
var serviceId = 'appModalService';
angular.module('app').factory(serviceId, [
'$ionicModal', '$rootScope', '$q', '$injector', '$controller', appModalService
]);
function appModalService($ionicModal, $rootScope, $q, $injector, $controller) {
return {
show: show
}
function show(templateUrl, controller, parameters) {
// Grab the injector and create a new scope
var deferred = $q.defer(),
ctrlInstance,
modalScope = $rootScope.$new(),
thisScopeId = modalScope.$id;
$ionicModal.fromTemplateUrl(templateUrl, {
scope: modalScope,
animation: 'slide-in-up'
}).then(function (modal) {
modalScope.modal = modal;
modalScope.openModal = function () {
modalScope.modal.show();
};
modalScope.closeModal = function (result) {
deferred.resolve(result);
modalScope.modal.hide();
};
modalScope.$on('modal.hidden', function (thisModal) {
if (thisModal.currentScope) {
var modalScopeId = thisModal.currentScope.$id;
if (thisScopeId === modalScopeId) {
deferred.resolve(null);
_cleanup(thisModal.currentScope);
}
}
});
// Invoke the controller
var locals = { '$scope': modalScope, 'parameters': parameters };
var ctrlEval = _evalController(controller);
ctrlInstance = $controller(controller, locals);
if (ctrlEval.isControllerAs) {
ctrlInstance.openModal = modalScope.openModal;
ctrlInstance.closeModal = modalScope.closeModal;
}
modalScope.modal.show();
}, function (err) {
deferred.reject(err);
});
return deferred.promise;
}
function _cleanup(scope) {
scope.$destroy();
if (scope.modal) {
scope.modal.remove();
}
}
function _evalController(ctrlName) {
var result = {
isControllerAs: false,
controllerName: '',
propName: ''
};
var fragments = (ctrlName || '').trim().split(/\s+/);
result.isControllerAs = fragments.length === 3 && (fragments[1] || '').toLowerCase() === 'as';
if (result.isControllerAs) {
result.controllerName = fragments[0];
result.propName = fragments[2];
} else {
result.controllerName = ctrlName;
}
return result;
}
} // end
})();
Usage:
appModalService
.show('<templateUrl>', '<controllerName> or <controllerName as ..>', <parameters obj>)
.then(function(result) {
// result from modal controller: $scope.closeModal(result) or <as name here>.closeModal(result) [Only on template]
}, function(err) {
// error
});
You can use another service to centralize the configuration of all modals:
angular.module('app')
.factory('myModals', ['appModalService', function (appModalService){
var service = {
showLogin: showLogin,
showEditUser: showEditUser
};
function showLogin(userInfo){
// return promise resolved by '$scope.closeModal(data)'
// Use:
// myModals.showLogin(userParameters) // get this inject 'parameters' on 'loginModalCtrl'
// .then(function (result) {
// // result from closeModal parameter
// });
return appModalService.show('templates/modals/login.html', 'loginModalCtrl as vm', userInfo)
// or not 'as controller'
// return appModalService.show('templates/modals/login.html', 'loginModalCtrl', userInfo)
}
function showEditUser(address){
// return appModalService....
}
}]);
You need to attach your models to the scope:
$scope.data.employeeName = "";
$scope.data.employeeAge = "";
...and similar every time you reference them.

Angular Two way databinding and http.post issue

Objective: Two Way Databinding between database and view via scope and controller
I’m trying to post to a restful database using angular
When I click on the thumbs up or thumbs down the scope changes o.k and is reflected in the view
However how can this placed in real time to a restful database using http post ?
Here’s the HTML
<div ng-controller="ordersCtrl">
<div class="span0 well votingWidget">
<div class="votingButton" ng-click="upVoteOrder(order)">
<i class="icon-thumbs-up "></i>
</div>
<div class="badge ">
<div>{{order.upVoteCount}}</div>
</div>
<div class="votingButton" ng-click="downVoteOrder(order)">
<i class="icon-thumbs-down"></i>
</div>
Heres the Controller: My issue lies here in the http.post command
.controller("ordersCtrl", function ($scope, $http, ordersUrl) {
$scope.downVoteOrder = function(order) {
$scope.selectedOrder = order;
order.upVoteCount--;
$http.post(orderUrl, order.upVoteCount)
.success(function (data) {
$scope.data.orderupVoteCount = data.id;
})
};
});
Note : I can post form data to the restful database successfully using the following code
$scope.sendOrder = function (shippingDetails) {
var order = angular.copy(shippingDetails);
order.products = cart.getProducts();
$http.post(orderUrl, order)
.success(function (data) {
$scope.data.orderId = data.id;
cart.getProducts().length = 0;
})
.error(function (error) {
$scope.data.orderError = error;
}).finally(function () {
$location.path("/uploaded");
});
}
you should use a separate service to handle the http post .
var app = angular.module("myApp", []);
app.factory("OrderService", ["$http", function ($http) {
this.PostDownVote = function(orderUrl, upVoteCount) {
return $http.post(orderUrl, upVoteCount);
}
this.PostOrder = function(orderUrl, order) {
// do something
}
return this;
}]);
Now inject this OrderService to you controller and use it.
app.controller("ordersCtrl", function ($scope, $http, ordersUrl, OrderService) {
$scope.downVoteOrder = function(order) {
$scope.selectedOrder = order;
order.upVoteCount--;
OrderService.PostDownVote(ordersUrl, order.upVoteCount)
.success(data) {// do something}
.error(data) {// do something}
}
});

Resources