ion-slide-box issues with modal in Ionic App - html

I am using ion-slider to show images and after clicking slide image get show full Image in ion-slider to sliding full image.
But I have problem when I back directly first full image to home screen then slider not working.
I have used following views and controllers.
Home Template View :
<ion-view view-title="Home">
<ion-content>
<div class="padding">
<ion-slide-box>
<ion-slide ng-repeat="Image in gallery" ng-click="showImages($index)" repeat-done="repeatDone()">
<img data-ng-src="{{sdcardpath}}{{Image.Path}}" width="100%"/>
<ion-slide>
</ion-slide-box>
</div>
</ion-content>
</ion-view>
Controller :
.controller('HomeController', function($scope,$cordovaFile,$ionicBackdrop, $ionicModal, $ionicSlideBoxDelegate, $ionicScrollDelegate, $ionicPopup, $timeout) {
$scope.sdcardpath = cordova.file.externalRootDirectory + foldername;
$scope.gallery = [
{ Path: 'img1.png' },
{ Path: 'img2.png' },
{ Path: 'img3.png' },
];
$scope.repeatDone = function() {
$ionicSlideBoxDelegate.update();
};
/*
* Show Full Screen Sliding Gallery Images
*/
$scope.showImages = function(index) {
$scope.activeSlide = index;
$scope.showModal('templates/image-popover.html');
};
$scope.showModal = function(templateUrl) {
$ionicModal.fromTemplateUrl(templateUrl, {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
$scope.modal.show();
});
};
$scope.zoomMin = 1;
$scope.updateSlideStatus = function(slide) {
var zoomFactor = $ionicScrollDelegate.$getByHandle('scrollHandle' + slide).getScrollPosition().zoom;
if (zoomFactor == $scope.zoomMin) {
$timeout(function(){
$ionicSlideBoxDelegate.enableSlide(true);
});
} else {
$timeout(function(){
$ionicSlideBoxDelegate.enableSlide(false);
});
}
};
}
Modal View : image-popover.html
<div class="modal image-modal">
<ion-slide-box active-slide="activeSlide" show-pager="false">
<ion-slide ng-repeat="Images in gallery">
<ion-scroll direction="xy" locking="false" scrollbar-x="false" scrollbar-y="false"
zooming="true" min-zoom="{{zoomMin}}" style="width: 100%; height: 100%"
delegate-handle="scrollHandle{{$index}}" on-scroll="updateSlideStatus(activeSlide)" on-release="updateSlideStatus(activeSlide)">
<img data-ng-src="{{sdcardpath}}{{Images.Path}}" width="100%"/>
</ion-scroll>
</ion-slide>
</ion-slide-box>
</div>
And Directive : repeatDone
.directive('repeatDone', function () {
return function (scope, element, attrs) {
if (scope.$last) { // all are rendered
scope.$eval(attrs.repeatDone);
}
}
So please help to solve this issues.

I got solution by some changes in Controller.
Controller
.controller('HomeController', function($scope,$cordovaFile,$ionicBackdrop, $ionicModal, $ionicSlideBoxDelegate, $ionicScrollDelegate, $ionicPopup, $timeout) {
$scope.sdcardpath = cordova.file.externalRootDirectory + foldername;
$scope.gallery = [
{ Path: 'img1.png' },
{ Path: 'img2.png' },
{ Path: 'img3.png' },
];
$scope.repeatDone = function() {
$ionicSlideBoxDelegate.update();
};
/*
* Show Full Screen Sliding Gallery Images
*/
$scope.showImages = function(index) {
$scope.activeSlide = index;
$scope.showModal('templates/image-popover.html');
};
$scope.showModal = function(templateUrl) {
$ionicModal.fromTemplateUrl(templateUrl, {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
$scope.modal.show();
});
};
//Cleanup the modal when we're done with it!
$scope.$on('$destroy', function() {
$scope.modal.remove();
$ionicSlideBoxDelegate.enableSlide(true);
$ionicSlideBoxDelegate.update();
});
// Execute action on hide modal
$scope.$on('modal.hidden', function() {
// Execute action
$ionicSlideBoxDelegate.enableSlide(true);
$ionicSlideBoxDelegate.update();
});
// Execute action on remove modal
$scope.$on('modal.removed', function() {
// Execute action
$ionicSlideBoxDelegate.enableSlide(true);
$ionicSlideBoxDelegate.update();
});
$scope.zoomMin = 1;
$scope.updateSlideStatus = function(slide) {
var zoomFactor = $ionicScrollDelegate.$getByHandle('scrollHandle' + slide).getScrollPosition().zoom;
if (zoomFactor == $scope.zoomMin) {
$timeout(function(){
$ionicSlideBoxDelegate.enableSlide(true);
});
} else {
$timeout(function(){
$ionicSlideBoxDelegate.enableSlide(false);
});
}
};
}

Related

Nested Directive Not Updating View(DOM) Element in AngularJs

I've made a nested directive, and tried to call it from a html view,but not updating the view element in html.
I can get the updated value from the calling controller but can't see the updated effect in view level.
Here is the Js
// Code goes here
"use strict";
var myApp=angular.module("myApp",[]);
myApp.directive("selectDirective", [function () {
return {
restrict: "E",
template: '<select class="form-control input-sm dropdown" data-ng-model="model.args.selectedItem" data-ng-options="item[model.args.displayField] for item in model.args.source" data-ng-change="model.itemChange(model.args.selectedItem)"><option value="">Select Any Item</option></select>',
scope: {
},
bindToController: { args: "=" },
link: function (scope, element, attrs) {
var self = scope.model || {};
var initializeControl = function () {
if (self.args == undefined) {
self.args = {};
}
if (self.args.method == undefined) {
self.args.method = {};
}
if (self.args.isDisabled == undefined) {
self.args.isDisabled = false;
}
if (self.args.displayField == undefined) {
self.args.displayField = '';
//alert('Display Field is blank for dropdown control.')
}
if (self.args.valueField == undefined) {
self.args.valueField = '';
//alert('Value Field is blank for dropdown control.')
}
if (self.args.source == undefined) {
self.args.source = {};
}
if (self.args.hide == undefined) {
self.args.hide = false;
}
}
var assignMethod = function () {
self.args.method =
{
setEnable: function (args) {
self.args.isDisabled = !args;
},
setVisible: function (args) {
self.args.hide = !args;
},
getText: function () {
return self.args.selectedText;
},
getValue: function () {
return self.args.selectedValue;
},
setItem: function (item) {
if (item != undefined) {
var index = self.args.source.indexOf(item);
self.args.selectedText = item[self.args.displayField];
self.args.selectedValue = item[self.args.valueField];
self.args.selectedItem = item;
self.args.selectedIndex = index;
}
}
}
}
self.itemChange = function (item) {
if (item != undefined) {
var index = self.args.source.indexOf(item);
self.args.selectedText = item[self.args.displayField];
self.args.selectedValue = item[self.args.valueField];
self.args.selectedItem = item;
self.args.selectedIndex = index;
}
}
initializeControl();
assignMethod();
},
controller: function () { },
controllerAs: 'model'
}
}]);
myApp.directive("stateDirective", [function () {
return {
restrict: "E",
template: '<select-directive args="model.args"></select-directive>',
scope: {},
bindToController: { args: "=" },
link: function (scope, element, attrs) {
var self = scope.model || {};
var initializeControl = function () {
if (self.args == undefined) {
self.args = {};
}
var sourceList = [{ id: 1, name: "AA", value: "AA" },
{ id: 2, name: "AB", value: "AB" },
{ id: 3, name: "ABD", value: "ABD" },
{ id: 4, name: "ABE", value: "ABE" },
{ id: 5, name: "ACT", value: "ACT" },
{ id: 6, name: "AE", value: "AE" }];
self.args.source = sourceList;
self.args.displayField = 'name';
self.args.valueField = 'value';
}();
},
controller: function () {
},
controllerAs: 'model'
}
}]);
myApp.controller("homeController", ['$interval', function ($interval) {
var self = this;
var initializeControl = function () {
self.state1 = {};
self.state2 = {};
self.ClickMe = function () {
debugger;
aler(1);
self.state2.method.setItem(self.state1.selectedItem);
}
self.ClickMe2 = function () {
debugger;
aler(1);
var x1 = self.state1;
var x2 = self.state2;
}
};
$interval(function () {
}, 500);
initializeControl();
}]);
Here is the Html:
<div class="cold-md-12" ng-controller="homeController as model">
<h1>Home Page</h1>
<state-directive args="model.state1"></state-directive>
<br />
<input type="button" value="ClickMe" data-ng-click="model.ClickMe()" />
<state-directive args="model.state2"></state-directive><br />
<input type="button" value="Submit" data-ng-click="model.ClickMe2()" />
</div>
Fiddle Here.
N.B: i tried using $watch and $timeout in directive and controller also but didn't work.
In the event that scope.model is not initialized, you're assigning {} to self in your linking function. But then you never actually place it on the controller. If scope.model exists, you're fine, because you're then binding everything to the controller, which is bound to scope, but if it's not stuff goes wrong. Which I'm guessing is what's happening.
Although, if I may be so bold, I'd say that naming your controller model is very misleading. Because in the development world models and controllers are two very different things.
Cheers,
Aaron
Just added track by in ng-option.
I just change the data-ng-options value
from
item[model.args.displayField] for item in model.args.source
to
item[model.args.displayField] for item in model.args.source track by item[model.args.valueField]
and it's working perfectly.

Angular js $parse does not work

I have written a directive by using typescript. here is my directive below.
'use strict';
module App.Directives {
interface IPageModal extends ng.IDirective {
}
interface IPageModalScope extends ng.IScope {
}
class PageModal implements IPageModal {
static directiveId: string = 'pageModal';
restrict: string = "A";
constructor(private $parse: ng.IParseService) {
}
link = (scope: IPageModalScope, element, attrs) => {
element.click((event) => {
event.preventDefault();
var options = {
backdrop: 'static',
keyboard: false
};
event.openModal = function () {
$('#' + attrs['targetModal']).modal(options);
};
event.showModal = function () {
$('#' + attrs['targetModal']).modal('show');
};
event.closeModal = function () {
$('#' + attrs['targetModal']).modal('hide');
};
var fn = this.$parse(attrs['pageModal']);
fn(scope, { $event: event });
});
}
}
//References angular app
app.directive(PageModal.directiveId, ['$parse', $parse => new PageModal($parse)]);
}
Use in HTML
<button class="btn blue-grey-900" target-modal="emplpyeeViewModal" page-modal="vm.addEmployee($event)">
<i class="icon-plus m-b-xs"></i>
</button>
Use in Controller
addEmployee($event) {
$event.openModal();
};
This line does not work. var fn = this.$parse(attrs['pageModal']); . I can not understand what is wrong. The error is
this.$parse is undefined.
and Service is called two times
It's quite trivial: your this is not your class'es scope because the function openmodal(event) { defines its own.
Declare the function on a class level or use arrow function instead, e.g.
link = (scope: IPageModalScope, element, attrs) => {
element.click((event) => {
event.preventDefault();
var options = {
backdrop: 'static',
keyboard: false
};
event.openModal = function () {
$('#' + attrs['targetModal']).modal(options);
};
event.showModal = function () {
$('#' + attrs['targetModal']).modal('show');
};
event.closeModal = function () {
$('#' + attrs['targetModal']).modal('hide');
};
var fn = this.$parse(attrs['pageModal']);//does not work here
fn(scope, { $event: event });
});
}

How to display a modelpopup window using angularJS?

I need to show a model popup window in a button click.can any one suggest the best method to achieve this in angularjs without BootstrpJS?
I tried the below and is not working. :(
html
<div>
<button ng-click='toggleModal()'>Add Dataset</button>
<modal-dialog info='modalShown' show='modalShown' width='400px' height='60%'>
<p>Modal Content Goes here</p>
</modal-dialog>
</div>
controller
app.controller('DataController', function ($scope,$http) {
$scope.showModal = false;
$scope.toggleModal = function () {
$scope.showModal = !$scope.showModal;
};
$http.get("/api/product").then(function (responses) {
$scope.ProductData = responses.data;
});
.......
........
});
app.directive('modalDialog', function () {
return {
restrict: 'E',
scope: {
show: '=info'
},
replace: true, // Replace with the template below
transclude: true, // we want to insert custom content inside the directive
link: function (scope, element, attrs) {
scope.dialogStyle = {};
if (attrs.width)
scope.dialogStyle.width = attrs.width;
if (attrs.height)
scope.dialogStyle.height = attrs.height;
scope.hideModal = function () {
scope.show = false;
};
},
template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay' ng-click='hideModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='hideModal()'>X</div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>"
};
});
It looks like you're messing with your scope a little too much. If you check out http://codepen.io/dboots/pen/vLeXPj, I used the same $scope.showModal variable and the same the same $scope.toggleModal function to show/hide.
angular.module('testApp', [])
.controller('DataController', function($scope) {
$scope.showModal = false;
$scope.toggleModal = function() {
$scope.showModal = !$scope.showModal;
};
})
.directive('modalDialog', function() {
return {
restrict: 'E',
replace: true, // Replace with the template below
transclude: true, // we want to insert custom content inside the directive
link: function(scope, element, attrs) {
scope.dialogStyle = {};
if (attrs.width)
scope.dialogStyle.width = attrs.width;
if (attrs.height)
scope.dialogStyle.height = attrs.height;
},
template: "<div class='ng-modal' ng-show='showModal'><div class='ng-modal-overlay' ng-click='toggleModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='toggleModal()'>X</div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>"
};
});
Make a directive. Then include it in your controller.
See: https://docs.angularjs.org/guide/directive

Angular-ui tooltip with HTML

I am currently adding some bootstrap tooltips in my application.
All of the "normal" tooltips are ok, but when I want to use tooltip-html-unsafe, all I got is an empty tooltip.
My tooltip:
<a><span tooltip-placement="right" tooltip-html-safe="{{myHTMLText}}"> Help </span></a>
In the DOM, I have:
<div class="tooltip-inner" ng-bind-html-unsafe="content"></div>
The div's content seems empty, so there is nothing to show in the tooltip. I tried to put directly in the DOM some HTML text like:
<div class="tooltip-inner" ng-bind-html-unsafe="content"><b>test</b></div> and it works.
Do you have an idea?
The html-unsafe directive is designed to point at it's content. What about this:
<div data-ng-controller="SomeCtrl">
<span data-tooltip-html-unsafe="{{yourContent}}" data-tooltip-placement="right">
Help
</span>
</div>
Then, in SomeCtrl, make a variable to hold the html:
$scope.yourContent = "<b>my html, yay</b>
IF you would like to modify bootstrap to take the content from a element, it can be done like this. First, you must change the tooltip template so that it calls a function to get the html:
angular.module("template/tooltip/tooltip-html-unsafe-popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/tooltip/tooltip-html-unsafe-popup.html",
"<div class=\"tooltip {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"tooltip-arrow\"></div>\n" +
" <div class=\"tooltip-inner\" ng-bind-html-unsafe=\"getToolTipHtml()\"></div>\n" +
"</div>\n" +
"");
}]);
Then, make a link function for the tooltipHtmlUnsafePopup:
.directive( 'tooltipHtmlUnsafePopup', function () {
return {
restrict: 'E',
replace: true,
scope: { content: '#', placement: '#', animation: '&', isOpen: '&' },
templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html',
link: function(scope, element, attrs) {
scope.getTooltipHtml = function() {
var elemId = '#' + scope.content;
var htmlContent = $rootElement.find(elemId).html();
return htmlContent;
};
}
};
})
EDIT: Later I extracted the customized code from ui-bootstrap, which is good since you do not have to modify ui-bootstrap to use it now. Here is the extracted code, in a module called "bootstrapx". This is just for popovers (as I was not really using tooltips) but I feel like this should be easily adaptable for tooltips too.
angular.module("bootstrapx", ["bootstrapx.tpls","bootstrapx.popover","bootstrapx.popover.dismisser"]);
angular.module("bootstrapx.tpls", ["template/popover/popover-html.html","template/popover/popover-html-unsafe.html","template/popover/popover-template.html"]);
angular.module( 'bootstrapx.popover', [ 'ui.bootstrap.tooltip' ] )
.directive('popover', [ function() {
return {
restrict: 'EA',
priority: -1000,
link: function(scope, element) {
element.addClass('popover-link');
}
};
}])
.directive('popoverHtml', [ function() {
return {
restrict: 'EA',
priority: -1000,
link: function(scope, element) {
element.addClass('popover-link');
}
};
}])
.directive('popoverHtmlUnsafe', [ function() {
return {
restrict: 'EA',
priority: -1000,
link: function(scope, element) {
element.addClass('popover-link');
}
};
}])
.directive('popoverTemplate', [ function() {
return {
restrict: 'EA',
priority: -1000,
link: function(scope, element) {
element.addClass('popover-link');
}
};
}])
.directive( 'popoverHtmlPopup', [ function() {
return {
restrict: 'EA',
replace: true,
scope: { title: '#', content: '#', placement: '#', animation: '&', isOpen: '&' },
templateUrl: 'template/popover/popover-html.html'
};
}])
.directive( 'popoverHtml', [ '$compile', '$timeout', '$parse', '$window', '$tooltip', function ( $compile, $timeout, $parse, $window, $tooltip ) {
return $tooltip( 'popoverHtml', 'popover', 'click' );
}])
.directive( 'popoverHtmlUnsafePopup', [ '$rootElement', function ( $rootElement ) {
return {
restrict: 'EA',
replace: true,
scope: { title: '#', content: '#', placement: '#', animation: '&', isOpen: '&' },
templateUrl: 'template/popover/popover-html-unsafe.html',
link: function(scope, element) {
var htmlContent = '';
scope.$watch('content', function(value) {
if (!value) {
return;
}
var elemId = '#' + value;
htmlContent = $rootElement.find(elemId).html();
});
scope.getPopoverHtml = function() {
return htmlContent;
};
}
};
}])
.directive( 'popoverHtmlUnsafe', [ '$compile', '$timeout', '$parse', '$window', '$tooltip', function ( $compile, $timeout, $parse, $window, $tooltip ) {
return $tooltip( 'popoverHtmlUnsafe', 'popover', 'click' );
}])
.directive( 'popoverTemplatePopup', [ '$http', '$templateCache', '$compile', '$parse', function ( $http, $templateCache, $compile, $parse) {
return {
restrict: 'EA',
replace: true,
scope: { title: '#', content: '#', placement: '#', animation: '&', isOpen: '&' },
templateUrl: 'template/popover/popover-template.html',
link: function(scope, element, attrs) {
scope.getPopoverTemplate = function() {
var templateName = scope.content + '.html';
return templateName;
};
}
};
}])
.directive( 'popoverTemplate', [ '$compile', '$timeout', '$parse', '$window', '$tooltip', function ( $compile, $timeout, $parse, $window, $tooltip ) {
return $tooltip( 'popoverTemplate', 'popover', 'click' );
}]);
angular.module("template/popover/popover-html.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/popover/popover-html.html",
"<div class=\"popover {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"arrow\"></div>\n" +
"\n" +
" <div class=\"popover-inner\">\n" +
" <h3 class=\"popover-title\" ng-bind=\"title\" ng-show=\"title\"></h3>\n" +
" <div class=\"popover-content\" ng-bind-html=\"content\"></div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/popover/popover-html-unsafe.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/popover/popover-html-unsafe.html",
"<div class=\"popover {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"arrow\"></div>\n" +
"\n" +
" <div class=\"popover-inner\">\n" +
" <h3 class=\"popover-title\" ng-bind=\"title\" ng-show=\"title\"></h3>\n" +
" <div class=\"popover-content\" ng-bind-html-unsafe=\"{{getPopoverHtml()}}\"></div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/popover/popover-template.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/popover/popover-template.html",
"<div class=\"popover {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"arrow\"></div>\n" +
"\n" +
" <div class=\"popover-inner\">\n" +
" <h3 class=\"popover-title\" ng-bind=\"title\" ng-show=\"title\"></h3>\n" +
" <div class=\"popover-content\" ng-include=\"getPopoverTemplate()\"></div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module('bootstrapx.popover.dismisser', [])
.directive( 'dismissPopovers', [ '$http', '$templateCache', '$compile', '$parse', function ( $http, $templateCache, $compile, $parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('mouseup', function(e) {
var clickedOutside = true;
$('.popover-link').each(function() {
if ($(this).is(e.target) || $(this).has(e.target).length) {
clickedOutside = false;
return false;
}
});
if ($('.popover').has(e.target).length) {
clickedOutside = false;
}
if (clickedOutside) {
$('.popover').prev().click();
}
});
}
};
}]);
I have the dismissPopovers directive on the body tag (this is likely applicable for tooltips too, you will just have to modify it to suit your needs):
<body data-ng-controller="AppController" data-dismiss-popovers>
I have created custom directive which allows html tooltips for bootsrap in very simple way. No need to override any templates:
angular.module('vermouthApp.htmlTooltip', [
])
.directive('vaTooltip', ['$http', '$templateCache', '$compile', '$parse', '$timeout', function ($http, $templateCache, $compile, $parse, $timeout)
{
//va-tooltip = path to template or pure tooltip string
//tooltip-updater = scope item to watch for changes when template has to be reloaded [optional (only if template is dynamic)]
//All other attributes can be added for standart boostrap tooltip behavior (ex. tooltip-placement)
return {
restrict: 'A',
scope: true,
compile: function (tElem, tAttrs)
{
//Add bootstrap directive
if (!tElem.attr('tooltip-html-unsafe'))
{
tElem.attr('tooltip-html-unsafe', '{{tooltip}}');
}
return function (scope, element, attrs)
{
scope.tooltip = attrs.vaTooltip;
var tplUrl = $parse(scope.tooltip)(scope);
function loadTemplate()
{
$http.get(tplUrl, { cache: $templateCache }).success(function (tplContent)
{
var container = $('<div/>');
container.html($compile(tplContent.trim())(scope));
$timeout(function ()
{
scope.tooltip = container.html();
});
});
}
//remove our direcive to avoid infinite loop
element.removeAttr('va-tooltip');
//compile element to attach tooltip binding
$compile(element)(scope);
if (angular.isDefined(attrs.tooltipUpdater))
{
scope.$watch(attrs.tooltipUpdater, function ()
{
loadTemplate();
});
} else
{
loadTemplate();
}
};
}
};
}]);
Thats how you call it
<a va-tooltip="'tooltipContent.html'" tooltip-updater="item" tooltip-placement="bottom">
<b><i>{{item.properties.length - propertyShowLimit + ' properties more...'}}</i></b>
</a>
And template can be like this:
<script id="tooltipContent.html" type="text/ng-template">
<span ng-repeat="prop in item.properties>
<b>{{prop.name}}</b>:
<span ng-repeat="val in prop.values">{{val.value}} </span>
<br />
</span>
</script>
There is now buit-in template functionality: https://angular-ui.github.io/bootstrap/#tooltip
Custom template
<script type="text/ng-template" id="myTooltipTemplate.html">
<span>Special Tooltip with <strong>markup</strong> and {{ dynamicTooltipText }}</span>
</script>

Jquery Mobile when redirecting or changing url, pages does not have any css

I am working with a backbone, jquery mobile, express app. Everything looks fine when the app starts and works correctly, however, when I click a link or change the url the html renders correctly but no jquery mobile magic appears. It only renders in the login part with a header and footer and format, but when the url changes and I come back, the page loses its css or jquery mobile magic.
define(['views/index', 'views/register', 'views/login', 'views/forgotpassword', 'views/profile',
'views/vinbookDoc', 'models/Account', 'models/Vinbook', 'models/vinBooksCollection'],
function(IndexView, RegisterView, LoginView, ForgotPasswordView, ProfileView,
vinbookDocView, Account, Vinbook, vinBooksCollection) {
var AppRouter = Backbone.Router.extend({
currentView: null,
routes: {
"index": "index",
"login": "login",
"desk/:id": "desk",
"profile/:id": "profile",
"register": "register",
"forgotpassword": "forgotpassword",
"vinbook/:id": "showVinbook"
},
initialize: function(){
$('.back').live('click', function(event) {
window.history.back();
return false;
});
this.firstPage = true;
},
showVinbook: function(id) {
var getCollection = new vinBooksCollection();
getCollection.url = '/accounts/me/vinbook';
this.changeView( new vinbookDocView({
collection: getCollection,
id: id
}));
getCollection.fetch();
},
changeView: function(page) {
this.currentView = page;
$(this.currentView.el).attr('data-role', 'page');
this.currentView.render();
$('body').append($(this.currentView.el));
var transition = $.mobile.defaultPageTransition;
// We don't want to slide the first page
if (this.firstPage) {
transition = 'none';
this.firstPage = false;
}
$.mobile.changePage($(this.currentView.el), {changeHash:false, transition: transition});
},
index: function() {
this.changeView(new IndexView() );
},
desk: function (id){
var model = new Account({id:id});
this.changeView(new ProfileView({model:model}));
model.fetch({ error: function(response){ console.log ('error'+JSON.stringify(response)); } });
console.log('works');
},
profile: function (id){
this.changeView(new IndexView() );
},
login: function() {
this.changeView(new LoginView());
},
forgotpassword: function() {
this.changeView(new ForgotPasswordView());
},
register: function() {
this.changeView(new RegisterView());
}
});
return new AppRouter();
});
require
require.config({
paths: {
jQuery: '/js/libs/jquery',
jQueryUIL: '/js/libs/jqueryUI',
jQueryMobile: '/js/libs/jqueryMobile',
Underscore: '/js/libs/underscore',
Backbone: '/js/libs/backbone',
models: 'models',
text: '/js/libs/text',
templates: '../templates',
jqm: '/js/jqm-config',
AppView: '/js/AppView'
},
shim: {
'jQueryMobile': ['jQuery', 'jqm' ],
'jQueryUIL': ['jQuery'],
'Backbone': ['Underscore', 'jQuery', 'jQueryMobile', 'jQueryUIL'],
'AppView': ['Backbone']
}
});
require(['AppView' ], function(AppView) {
AppView.initialize();
});
login
define(['AppView','text!templates/login.html'], function(AppView, loginTemplate) {
window.loginView = AppView.extend({
requireLogin: false,
el: $('#content'),
events: {
"submit form": "login"
},
initialize: function (){
$.get('/login', {}, function(data){});
},
login: function() {
$.post('/login', {
email: $('input[name=email]').val(),
password: $('input[name=password]').val()
},
function(data) {
console.log(data);
if (!data.error){window.location.replace('#desk/me');}
}).error(function(){
$("#error").text('Unable to login.');
$("#error").slideDown();
});
return false;
},
render: function() {
this.$el.html(loginTemplate);
$("#error").hide();
return this;
}
});
return loginView;
});
Just some more details:
When I change from page or the url to another page, a flash of the rendered website appears and then the css or design disappears.
I think this can solve your problem:
$(document).bind('pagechange', function() {
$('.ui-page-active .ui-listview').listview('refresh');
$('.ui-page-active :jqmData(role=content)').trigger('create');
});