how can i update the template view or json data so that i could re-render my template view in backbone.js - backbone.js

i want to update the view, as i click on follow button, id for follow button is btn-follow.
i want to update the ui if template, that i when i click on follow button, if value in console data is true follow button should change in "FOLLOW" if value in console is false then button caption should be UN-FOLLOW. how can i update the view or how can i update the joson data and re-render the template.
my view code is here.
spine.module("communityApp", function (communityApp, App, Backbone, Marionette, $, _) {
// Load template
var pforumTemplateHtml = App.renderTemplate("pforumTemplate", {}, "communityModule/tabContainer/pforum");
// Define view(s)
communityApp.Views.pforumView = Marionette.ItemView.extend({
template: Handlebars.compile($(pforumTemplateHtml).html()),
tagName: "li",
onRender: function () {
this.object = this.model.toJSON();
},
events: {
"click .btn-comment" : "showComments",
"click #recent-btn": "recent",
"click #my-posts": "myposts",
"click #popular-btn": "popular",
"click #follow-btn": "follow",
"click #my-posts": "LeftLinks",
"click #popular-btn": "LeftLinks",
"click .btn-follow": "activityBtn",
"click #like-btn" : "activityBtn",
"click #post-comments-btn": "showCommentEiditor"
},
postcomments : function ()
{
$("#recent-post-main-container").hide();
$("#recent-post-main-container2").show();
},
showCommentEiditor : function (){
$(".comment-popup-container").show();
$(".comment-txt-area").val('');
},
showPforumTab : function ()
{
$("#recent-post-main-container2").show();
$("#recent-post-main-container").hide();
},
showComments : function(){
$("#loading").show();
$(".tab-pane").hide();
$(".left-content").hide();
$("#recent-post-main-container2").show();
$(".left-content-commentEditor").show();
//$(".comm-tab-content-container").css('height','200px');
$(".comment-txt-area").val('');
$(".left-content-comment").show();
},
hideCommentPopup : function ()
{
$("#public-question-comment").hide();
},
// Show Loading sign
showLoading : function () {
$('#loading').show();
},
// UnLoading Function
hideLoading : function (){
$('#loading').hide();
},
// Add New Event Function
addEvent : function()
{
//$("#name").val(getBackResponse.user.FullName);
//$("#phone").val(getBackResponse.user.CellPhone);
//$("#email").val(getBackResponse.user.UserName);
$(".overly.addevent").show();
$('#lang').val(lat);
$('#long').val(long);
document.getElementById("my-gllpMap").style.width = "100%";
var my_gllpMap = document.getElementById("my-gllpMap");
google.maps.event.trigger( my_gllpMap, "resize" );
},
setValues : function(key,value)
{
window.localStorage.setItem(key,value);
},
getValues : function (key)
{
return window.localStorage.getItem(key);
},
closeAddEvent:function ()
{
$(".overly.addevent").hide();
},
// Show Over lay
showOverly:function ()
{
$('.overly-right-tab').show();
},
// Hide Loading sign
hideOverly : function()
{
$('.overly-right-tab').hide();
},
enlargeImage : function ()
{
$('#image').css('width','212px');
$('#image').css('height','150px');
},
activityBtn: function (e) {
var elem = $(e.target);
if (elem.hasClass('inactive')) {
return false;
}
var activity = elem.attr('name');
switch (activity) {
case "like-Button":
var _this = $.extend({},this,true);
_this.activity = 'like-Button';
this.activityBtnSubmit.call(_this);
break;
//
case "follow-button":
var _this = $.extend({},this,true);
_this.activity = 'follow-button';
this.activityBtnSubmit.call(_this);
break;
}
},
//For Like Post
activityBtnSubmit: function (modalThis) {
// var o = (this.parentThis) ? this.parentThis.object : this.object;
//var o = "52fa2ccc9bca9ac90c000051";
var func = _.bind(function () {
//var hmObj = new MessageApp.Controllers.hmAlertsController();
//hmObj.init();
}, this);
switch (this.activity) {
case "like-Button":
App.ids = null;
App.ids2 = null;
App.ids = this.object.id;
App.ids2 = this.object.iLiked;
if(App.ids2 === true) {
App.action = 0;
}
else if(App.ids2 === false) {
App.action = 1;
}
var data = {
id: this.object.id,
iLiked:App.action,
sessionToken:loginUser.sessionToken,
};
$.when(App.request('alertActivity:entities', {
origin: 'pforum',
id: this.object.id,
iLiked:(App.action),
sessionToken:loginUser.sessionToken,
//value : value,
dataToSend: JSON.stringify(data),
activity:this.activity,
}))
.then(func);
App.ids1 = (data.id);
break;
case "follow-button":
App.ids = null;
App.ids2 = null;
App.ids = this.object.UserId;
App.ids2 = this.object.iFollow;
if(App.ids2 === true) {
// $(".btn-follow").html("UN-FOLLOW");
App.action = 0;
}
else if(App.ids2 === false) {
//$(".btn-follow").html("FOLLOW");
App.action = 1;
}
if (App.ids) {
alert (App.ids);
$(".btn-follow").html("UN-FOLLOW");
//App.action = 0;
}
else
{
$(".btn-follow").html("FOLLOW");
//App.action = 1;
}
var data = {
id: this.object.UserId,
iFollow:App.action,
sessionToken:loginUser.sessionToken,
};
$.when(App.request('alertActivity:entities', {
origin: 'pforum',
id: this.object.UserId,
iFollow:(App.action),
sessionToken:loginUser.sessionToken,
//value : value,
dataToSend: JSON.stringify(data),
activity:this.activity,
}))
.then(func);
App.ids1 = (data.UserId);
break;
}
return true;
}
});
var RowView = Backbone.View.extend({
events: {
"click .btn-follow": function() {console.log(this.model.get("name"));}
},
initialize: function(){
this.model.on('change', this.render, this);
},
render: function() {
var html=_.template(rowTemplate,this.model.toJSON());
this.setElement( $(html) );
return this;
},
});
// define collection views to hold many communityAppView:
communityApp.CollectionViews.pforumCollectionViews = Marionette.CollectionView.extend({
tagName: "ul",
itemView: communityApp.Views.pforumView
});
});
my template code is here.
<div>
<div class="comm-tab-row">
<div class="post-left-panel">
<div class="post-image-container">
<img src="{{UserImageURL}}" alt="" class="post-image" /></br>
{{#if iLiked}}
<img src="images/myCommunity/liked#2x.png" width="20" height="19" id="like-btn" name = "like-Button" >
{{else}}
<img src="images/myCommunity/like#2x.png" width="20" height="19" id="like-btn" name = "like-Button" >
{{/if}}
({{NumLikes}})
</div>
</div>
<div class="post-body">
<h5 class="comm-tab-heading">
<span class="navigate-screen" id="{{Id}}" style="text-decoration:underline;">
{{UserName}}
</span>
<span>
-
</span>
<span>
{{format_date Time ""}}
</span>
</h5>
{{Message}}
</div>
<div class="comm-right-panel">
{{#if iFollow}}
UN-FOLLOW
{{else}}
FOLLOW
{{/if}}
{{NumComments}} - COMMENT
</div>
</div>

You can add a new boolean to the model of your view isFollowing. You can then add a condition inside your template to determine which button to render.
<% if(isFollowing){ %>
<button> Unfollow </button>
<% } else { %>
<button> Follow</button>
<% } %>
To rerender the view call the render function from your event handler.
events: {
"click .btn-follow": function() {
//Do comething useful..
this.render();
}
},

Related

AngularJS - update ng-repeat list in DOM instantly to allow animation

I have a list to which I can add languages. When a language is added, there is an animation for maximum eye candy sexyness. The animation is triggered by a state change in ng-show="lang.visible" in the HTML. I have to first add the language to the language array, and THEN change the visible state to true for the animation to show.
The problem is, when I add the language to the array, it takes around 700 ms for the DOM to get updated, and then I change the state of visible. Those 700 ms make the page feel slow.
$scope.addTourDescLang = function(newLang) {
newLang.visible = false;
$scope.newClient.tours.languages.push(newLang);
$timeout(function() {
newLang.visible = true;
}, 700 );
};
Here's the animation code:
<script>
app.animation('.slide-toggle', ['$animateCss', function($animateCss) {
var lastId = 0;
var _cache = {};
function getId(el) {
var id = el[0].getAttribute("data-slide-toggle");
if (!id) {
id = ++lastId;
el[0].setAttribute("data-slide-toggle", id);
}
return id;
}
function getState(id) {
var state = _cache[id];
if (!state) {
state = {};
_cache[id] = state;
}
return state;
}
function generateRunner(closing, state, animator, element, doneFn) {
return function() {
state.animating = true;
state.animator = animator;
state.doneFn = doneFn;
animator.start().finally(function() {
if (closing && state.doneFn === doneFn) {
element[0].style.height = '';
}
element[0].style.height = 'auto';
state.animating = false;
state.animator = undefined;
state.doneFn();
});
}
}
return {
addClass: function(element, className, doneFn) {
if (className == 'ng-hide') {
var state = getState(getId(element));
var height = (state.animating && state.height) ?
state.height : element[0].offsetHeight;
var animator = $animateCss(element, {
from: {height: height + 'px'},
to: {height: '0px'}
});
if (animator) {
if (state.animating) {
state.doneFn =
generateRunner(true,
state,
animator,
element,
doneFn);
return state.animator.end();
}
else {
state.height = height;
return generateRunner(true,
state,
animator,
element,
doneFn)();
}
}
}
doneFn();
},
removeClass: function(element, className, doneFn) {
if (className == 'ng-hide') {
var state = getState(getId(element));
var height = (state.animating && state.height) ?
state.height : element[0].offsetHeight;
var animator = $animateCss(element, {
from: {height: '0px'},
to: {height: height + 'px'}
});
if (animator) {
if (state.animating) {
state.doneFn = generateRunner(false,
state,
animator,
element,
doneFn);
return state.animator.end();
}
else {
state.height = height;
return generateRunner(false,
state,
animator,
element,
doneFn)();
}
}
}
doneFn();
}
};
}]);
(function() {
var app = angular.module('app', ['ngAnimate']);
app.animation('.slide-toggle', ['$animateCss', function($animateCss) {
return {
addClass: function(element, className, doneFn) {
if (className == 'ng-hide') {
var animator = $animateCss(element, {
to: {height: '0px'}
});
if (animator) {
return animator.start().finally(function() {
element[0].style.height = '';
doneFn();
});
}
}
doneFn();
},
removeClass: function(element, className, doneFn) {
if (className == 'ng-hide') {
var height = element[0].offsetHeight;
var animator = $animateCss(element, {
from: {height: '0px'},
to: {height: height + 'px'}
});
if (animator) {
return animator.start().finally(doneFn);
}
}
doneFn();
}
};
}]);
})();
</script>
The CSS:
.slide-toggle {
overflow: hidden;
transition: all 0.25s;
}
The HTML:
<table class="table-list">
<tbody ng-repeat="langAdded in newClient.tours.languages">
<tr>
<td>
<div ng-show="langAdded.added" class="table-list-content slide-toggle">
<div>
<img ng-src="/images/icons/flags/flag-{{ langAdded.code }}-30x20.png" style="vertical-align: middle; margin: 0 10px 0 20px;">
{{ langAdded.title }}
</div>
</div>
</td>
<td>
<div ng-show="langAdded.added" class="slide-toggle">
<md-button class="md-icon-button remove-icon-button" ng-click="removeTourDescLang(langAdded)" aria-label="Remove">
<md-icon md-svg-icon="/images/icons/svg/cross-close.svg"></md-icon>
</md-button>
</div>
</td>
</tr>
</tbody>
</table>
How can this be done in a better way?
How can I update DOM instantly, and then directly after changing the visible state to true?

Angularjs toolbar commands- disable and disable buttons

I am trying to disable and enable button:
for instance: If I click on Modify button I want to disable it and Enable Save button and if I click on Save button I want to enable Modify button and disable Save button. Thank you.
Below the Angularjs code:
angular.module('virtoCommerce.catalogModule')
.controller('virtoCommerce.catalogModule.categoriesItemsListController', ['$scope', function ($scope) {
var isFieldEnabled = true;
blade.updatePermission = 'catalog:update';
... (more codes but not included)
var formScope;
$scope.setForm = function (form) { formScope = form; }
//Save the prices entered by the user.
function savePrice()
{
//TODO: Save the price information.
}
function isDirty() {
return blade.hasUpdatePermission();
};
//function enablePriceField
function enablePriceField() {
var inputList = document.getElementsByTagName("input");
var inputList2 = Array.prototype.slice.call(inputList);
if (isFieldEnabled == true) {
for (i = 0; i < inputList.length; i++) {
var row = inputList2[i];
if (row.id == "priceField") {
row.disabled = false;
}
}
} else {
for (i = 0; i < inputList.length; i++) {
var row = inputList2[i];
if (row.id == "priceField") {
row.disabled = true;
}
}
}
//Set the flag to true or false
if (isFieldEnabled == true) {
isFieldEnabled = false
} else {
isFieldEnabled = true;
}
}
var formScope;
$scope.setForm = function (form) { formScope = form; }
function canSave() {
return isDirty() && formScope && formScope.$valid;
}
//Angular toolbar commands
blade.toolbarCommands = [
{
name: "platform.commands.modify",
icon: 'fa fa-pencil',
executeMethod: function () { enablePriceField();},
canExecuteMethod: function () { return true; }
},
{
name: "platform.commands.save",
icon: 'fa fa-floppy-o',
executeMethod: function () { savePrice(); },
canExecuteMethod: canSave,
permission: blade.updatePermission
}];
}]);
I am not sure I see how your code is related to the question, but you can enable/disable a button programatically using the ngDisabled directive (see the docs).
In your controller, intialize $scope.enableSave = true (of false, as you want). Then in your html:
<button class="btn btn-primary" ng-disabled="!enableSave" ng-click="enableSave=!enableSave">Save</button>
<button class="btn btn-primary" ng-disabled="enableSave" ng-click="enableSave=!enableSave">Modify</button>
You will toggle 'enableSave' each time you click on the active (ie. not disabled) button, which will in turn disable the button you just clicked, and enable the other one.
Sorry, I had not seen... I am not familiar with virtoCommerce, but if I understand correctly you want to update the 'canExecuteMethod' ? Maybe try something like that:
$scope.enableSave = false;
function canSave() {
return isDirty() && formScope && formScope.$valid && $scope.enableSave;
}
Then for the buttons:
{
name: "platform.commands.modify",
icon: 'fa fa-pencil',
executeMethod: function () {
enablePriceField();
$scope.enableSave = true;
},
canExecuteMethod: function () { return !canSave(); }
},
{
name: "platform.commands.save",
icon: 'fa fa-floppy-o',
executeMethod: function () {
savePrice();
$scope.enableSave = false;
},
canExecuteMethod: function () { return canSave(); },
permission: blade.updatePermission
}
As a side note, if isFieldEnabled is a boolean you can replace:
if (isFieldEnabled == true) {
isFieldEnabled = false
} else {
isFieldEnabled = true;
}
By: isFieldEnabled = !isFieldEnabled;

v-for and computed properties calling methods

I'm trying to update some properties on a VueJS object list, but I'm having some glitches.
Here's the HTML:
<div id="el">
<p>Total Chats: {{ chats.length }} ({{ unreadCount }} unread)</p>
<button v-on:click="__addChat(true)">Add a Chat</button>
<button v-on:click="__makeAllRead">Read All</button>
<pre>{{ $data | json }}</pre>
<ul>
<li v-for="chat in chats">
<p>
Message {{ chat.id }}
<span v-if="chat.unread"><strong>(UNREAD)</strong></span>
</p>
</li>
</ul>
</div>
And the Vue code:
var vm = new Vue({
el: '#el',
data: {
nextID : 2,
chats: {
'6fc5gh4j3kl_FIRST': {
id : 1,
unread : true,
body : Date(),
}
},
},
methods: {
__addChat: function (unread) {
var chat = {
id : this.nextID++,
unread : unread,
body : Date(),
};
this.chats[this.__makeHash()] = chat;
console.log(this.chats);
},
__makeAllRead : function() {
console.log(Object.keys(this.chats));
for ( var key in Object.keys(this.chats) ) {
// if any tests are invalid
if ( this.chats.hasOwnProperty(key) ) {
this.chats[key] = true;
}
}
},
__countUnread : function() {
var unread = 0;
for ( var key in Object.keys(this.chats) ) {
// if any tests are invalid
if ( this.chats.hasOwnProperty(key) && this.chats[key].unread ) {
unread++;
}
}
return unread;
},
__makeHash: function() {
return '6fc5gh4j3kl1AZ0' + Math.floor((Math.random() * 100) + 1);
},
},
ready: function() {
this.__addChat(false);
},
computed: {
unreadCount: function () {
console.log('counting...');
return this.countUnread();
}
}
});
Here's a Fiddle: http://jsfiddle.net/522aw2n5/7/
Things I cannot understand/fix on this code:
1) A computed property using a method to update the count
2) It displays only the object manually created, not the dynamically ones.
3) I cannot make all messages read by clicking a button.
This is Vue 1.0.0 RC2.
Could you, please, tell me what Am I doing wrong?
Answered on VueJS's Gitter
HTML
<div id="el">
<p>Total Chats: {{ totalChats }} ({{ unreadCount }} unread)</p>
<button v-on:click="__addChat(true)">Add a Chat</button>
<button v-on:click="__makeAllRead">Read All</button>
<pre>{{ $data | json }}</pre>
<ul>
<li v-for="chat in chats">
<p>
{{ chat.id }}
<span v-if="chat.unread"><strong>(UNREAD)</strong></span>
</p>
</li>
</ul>
</div>
Vue Code
var vm = new Vue({
el: '#el',
data: {
nextID : 2,
chats: {
'6fc5gh4j3kl_FIRST': {
id : 1,
unread : true,
body : Date(),
}
},
},
methods: {
__addChat: function (unread) {
var chat = {
id : this.nextID++,
unread : unread,
body : Date(),
};
this.$set('chats.' + this.__makeHash(), chat);
},
__makeAllRead : function() {
console.log(Object.keys(this.chats));
for ( var key in this.chats ) {
// if any tests are invalid
if ( this.chats.hasOwnProperty(key) ) {
this.chats[key].unread = false;
}
}
},
__makeHash: function() {
return 'fc5gh4j3kl1AZ0' + Math.floor((Math.random() * 100) + 1);
},
},
ready: function() {
this.__addChat(false);
},
computed: {
totalChats: function() {
var size = 0, key;
for (key in this.chats) {
if (this.chats.hasOwnProperty(key)) size++;
}
return size;
},
unreadCount: function () {
var unread = 0;
for ( var key in this.chats ) {
// if any tests are invalid
if ( this.chats.hasOwnProperty(key) && this.chats[key].unread ) {
unread++;
}
}
return unread;
}
}
});

How to Keep track of all clicks on page in ionic application?

I have created simple page which contains check boxes. On this page user can check and uncheck boxes multiple times. I want to keep track of all these events? How Can I do that?
here is my code.
app.js
var pmApp = angular.module('pmApp', ['ionic']);
pmApp.controller('CheckboxController', function($scope) {
$scope.devList = [
{ text: "Device & app history", details : "Allows the app to view one or more of: information about activity on the device, which apps are running, browsing history and bookmarks" ,checked: true },
{ text: "Identity", details: "Uses one or more of: accounts on the device, profile data", checked: false },
{ text: "Calendar", details: "Uses calendar information", checked: false },
{ text: "Contact", details: "Uses contact information", checked: false },
{ text: "Location", details: "Uses the device's location", checked: false },
{ text: "SMS", details: "Uses one or more of: SMS, MMS. Charges may apply.", checked: false }
];
$scope.selection=[];
// toggle selection for a given employee by name
$scope.toggleSelection = function toggleSelection(item) {
var idx = $scope.selection.indexOf(item);
// is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// is newly selected
else {
$scope.selection.push(item);
}
};
});
index.html
<div class="list" ng-controller="CheckboxController">
<ion-checkbox ng-repeat="item in devList"
ng-model="item.checked"
ng-checked="selection.indexOf(item) > -1"
ng-click="toggleSelection(item)"
>
{{ item.text }}
<h3 class="item-text-wrap"> {{ item.details }}</h3>
</ion-checkbox>
<div class="item">
<pre ng-bind="selection | json"></pre>
</div>
</div>
Thanks in advance, any help would be appreciated.
Regards
You can use https://docs.angularjs.org/api/ng/directive/ngMouseover to make a counter for mouse hovers on all your elements: and then use
https://docs.angularjs.org/api/ng/directive/ngClick to record clicks and https://docs.angularjs.org/api/ng/directive/ngMousemove to record the mouse being moved and get the position:
Everything Used:
ng-click
ng-dblclick
ng-mousedown
ng-mouseup
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
Here is some example code:
HTML:
<body ng-app="mainModule">
<div ng-controller="mainController">
<h3>1. Click</h3>
<button id="firstBtn" ng-click="onFirstBtnClick()">Click me</button>
<strong>RESULT:</strong> {{onFirstBtnClickResult}}<br />
<br />
<h3>2. Click with Dependency Injection</h3>
<label>Type something: <input type="text" ng-model="secondBtnInput"></label>
<button id="secondBtn" ng-click="onSecondBtnClick(secondBtnInput)">Click me</button><br />
<strong>RESULT:</strong> {{onSecondBtnClickResult}}<br />
<br />
<h3>3. Double click</h3>
Double-click the square<br />
<img src="images/square.png" ng-dblclick="onDblClick()" /><br />
<strong>RESULT:</strong> {{onDblClickResult}}<br />
<h3>4. Mouse down, up, enter, leave, move, over</h3>
Move the mouse on the square<br />
<img src="images/square.png"
ng-mousedown="onMouseDown($event)"
ng-mouseup="onMouseUp($event)"
ng-mouseenter="onMouseEnter($event)"
ng-mouseleave="onMouseLeave($event)"
ng-mousemove="onMouseMove($event)"
ng-mouseover="onMouseOver($event)" /><br />
<strong>MOUSE DOWN RESULT:</strong> {{onMouseDownResult}}<br />
<strong>MOUSE UP RESULT:</strong> {{onMouseUpResult}}<br />
<strong>MOUSE ENTER RESULT:</strong> {{onMouseEnterResult}}<br />
<strong>MOUSE LEAVE RESULT:</strong> {{onMouseLeaveResult}}<br />
<strong>MOUSE MOVE RESULT:</strong> {{onMouseMoveResult}}<br />
<strong>MOUSE OVER RESULT:</strong> {{onMouseOverResult}}
</div>
</body>
</html>
JS
angular.module("mainModule", [])
.controller("mainController", function ($scope)
{
// Initialization
$scope.onFirstBtnClickResult = "";
$scope.secondBtnInput = "";
$scope.onDblClickResult = "";
$scope.onMouseDownResult = "";
$scope.onMouseUpResult = "";
$scope.onMouseEnterResult = "";
$scope.onMouseLeaveResult = "";
$scope.onMouseMoveResult = "";
$scope.onMouseOverResult = "";
// Utility functions
// Accepts a MouseEvent as input and returns the x and y
// coordinates relative to the target element.
var getCrossBrowserElementCoords = function (mouseEvent)
{
var result = {
x: 0,
y: 0
};
if (!mouseEvent)
{
mouseEvent = window.event;
}
if (mouseEvent.pageX || mouseEvent.pageY)
{
result.x = mouseEvent.pageX;
result.y = mouseEvent.pageY;
}
else if (mouseEvent.clientX || mouseEvent.clientY)
{
result.x = mouseEvent.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
result.y = mouseEvent.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
if (mouseEvent.target)
{
var offEl = mouseEvent.target;
var offX = 0;
var offY = 0;
if (typeof(offEl.offsetParent) != "undefined")
{
while (offEl)
{
offX += offEl.offsetLeft;
offY += offEl.offsetTop;
offEl = offEl.offsetParent;
}
}
else
{
offX = offEl.x;
offY = offEl.y;
}
result.x -= offX;
result.y -= offY;
}
return result;
};
var getMouseEventResult = function (mouseEvent, mouseEventDesc)
{
var coords = getCrossBrowserElementCoords(mouseEvent);
return mouseEventDesc + " at (" + coords.x + ", " + coords.y + ")";
};
// Event handlers
$scope.onFirstBtnClick = function () {
$scope.onFirstBtnClickResult = "CLICKED";
};
$scope.onSecondBtnClick = function (value) {
$scope.onSecondBtnClickResult = "you typed '" + value + "'";
};
$scope.onDblClick = function () {
$scope.onDblClickResult = "DOUBLE-CLICKED";
};
$scope.onMouseDown = function ($event) {
$scope.onMouseDownResult = getMouseEventResult($event, "Mouse down");
};
$scope.onMouseUp = function ($event) {
$scope.onMouseUpResult = getMouseEventResult($event, "Mouse up");
};
$scope.onMouseEnter = function ($event) {
$scope.onMouseEnterResult = getMouseEventResult($event, "Mouse enter");
};
$scope.onMouseLeave = function ($event) {
$scope.onMouseLeaveResult = getMouseEventResult($event, "Mouse leave");
};
$scope.onMouseMove = function ($event) {
$scope.onMouseMoveResult = getMouseEventResult($event, "Mouse move");
};
$scope.onMouseOver = function ($event) {
$scope.onMouseOverResult = getMouseEventResult($event, "Mouse over");
};
});
You could try with the newest Ionic Analytics, if that will suit your needs. More info on their official blog post: http://docs.ionic.io/v1.0/docs/analytics-from-scratch.
Usage is pretty straight forward (from the additional docs):
.controller('MyCtrl', function($ionicAnalytics) {
$ionicAnalytics.track('Purchase Item', {
item_id: 'lpdsx,
item_name: 'Leopard Socks'
});
});

How to do the Logic behind the next button in angularjs wizard

I have a customers.create.html partial bound to the WizardController.
Then I have 3 customers.create1,2,3.html partial files bound to WizardController1,2,3
Each WizardController1,2 or 3 has an isValid() function. This function determines wether the user can proceed to the next step.
The next button at the bottom of the pasted html should be disabed if ALL ? isValid() functions are false...
Thats my question but the same time that seems not correct to me.
I guess I am not doing the Wizard correctly...
Can someone please guide me how I should proceed with the architecture that the bottom next button is disabled when the current step isValid function returns false, please.
How can I make a connection from the WizardController to any of the WizardController1,2 or 3 ?
Is Firing an event like broadcast a good direction?
<div class="btn-group">
<button class="btn" ng-class="{'btn-primary':isCurrentStep(0)}" ng-click="setCurrentStep(0)">One</button>
<button class="btn" ng-class="{'btn-primary':isCurrentStep(1)}" ng-click="setCurrentStep(1)">Two</button>
<button class="btn" ng-class="{'btn-primary':isCurrentStep(2)}" ng-click="setCurrentStep(2)">Three</button>
</div>
<div ng-switch="getCurrentStep()" ng-animate="'slide'" class="slide-frame">
<div ng-switch-when="one">
<div ng-controller="WizardController1" ng-include src="'../views/customers.create1.html'"></div>
</div>
<div ng-switch-when="two">
<div ng-controller="WizardController2" ng-include src="'../views/customers.create2.html'"></div>
</div>
<div ng-switch-when="three">
<div ng-controller="WizardController3" ng-include src="'../views/customers.create3.html'"></div>
</div>
</div>
<a class="btn" ng-click="handlePrevious()" ng-show="!isFirstStep()">Back</a>
<a class="btn btn-primary" ng-disabled="" ng-click="handleNext(dismiss)">{{getNextLabel()}}</a>
'use strict';
angular.module('myApp').controller('WizardController', function($scope) {
$scope.steps = ['one', 'two', 'three'];
$scope.step = 0;
$scope.wizard = { tacos: 2 };
$scope.isFirstStep = function() {
return $scope.step === 0;
};
$scope.isLastStep = function() {
return $scope.step === ($scope.steps.length - 1);
};
$scope.isCurrentStep = function(step) {
return $scope.step === step;
};
$scope.setCurrentStep = function(step) {
$scope.step = step;
};
$scope.getCurrentStep = function() {
return $scope.steps[$scope.step];
};
$scope.getNextLabel = function() {
return ($scope.isLastStep()) ? 'Submit' : 'Next';
};
$scope.handlePrevious = function() {
$scope.step -= ($scope.isFirstStep()) ? 0 : 1;
};
$scope.handleNext = function(dismiss) {
if($scope.isLastStep()) {
dismiss();
} else {
$scope.step += 1;
}
};
});
durandalJS wizard sample code which could be used to rewrite a wizard for angularJS:
define(['durandal/activator', 'viewmodels/step1', 'viewmodels/step2', 'knockout', 'plugins/dialog', 'durandal/app', 'services/dataservice'],
function (activator, Step1, Step2, ko, dialog, app, service) {
var ctor = function (viewMode, schoolyearId) {
debugger;
if (viewMode === 'edit') {
service.editSchoolyear(schoolyearId);
}
else if (viewMode === 'create') {
service.createSchoolyear();
}
var self = this;
var steps = [new Step1(), new Step2()];
var step = ko.observable(0); // Start with first step
self.activeStep = activator.create();
var stepsLength = steps.length;
this.hasPrevious = ko.computed(function () {
return step() > 0;
});
self.caption = ko.observable();
this.activeStep(steps[step()]);
this.hasNext = ko.computed(function () {
if ((step() === stepsLength - 1) && self.activeStep().isValid()) {
// save
self.caption('save');
return true;
} else if ((step() < stepsLength - 1) && self.activeStep().isValid()) {
self.caption('next');
return true;
}
});
this.isLastStep = function() {
return step() === stepsLength - 1;
}
this.next = function() {
if (this.isLastStep()) {
$.when(service.createTimeTable())
.done(function () {
app.trigger('savedTimeTable', { isSuccess: true });
})
.fail(function () {
app.trigger('savedTimeTable', { isSuccess: false });
});
}
else if (step() < stepsLength) {
step(step() + 1);
self.activeStep(steps[step()]);
}
}
this.previous = function() {
if (step() > 0) {
step(step() - 1);
self.activeStep(steps[step()]);
}
}
}
return ctor;
});

Resources