Angularjs toolbar commands- disable and disable buttons - angularjs

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;

Related

checking values against an array

I am a newbie struggling with Angular JS.
I am trying to make a questionaire and have the following code but keep getting the feedback for incorrect no matter what I try.
I have assigned a numeric value to each of four buttons, the titles of which are being pulled through from an array. I want to check the value of the selected button against the correct answer in the array. Can someone tell me where I am going wrong?
HTML
<div id="ansblock">
<button type="button" ng-click="myAnswer=0">{{options [0]}} </button>
<button type="button" ng-click="myAnswer=1">{{options [1]}}</button>
<button type="button" ng-click="myAnswer=2">{{options [2]}}</button>
<button type="button" ng-click="myAnswer=3">{{options [3]}}</button>
<p>Test to show button click value working {{myAnswer}}</p>
</div>
<button ng-click="checkAnswer()">Submit</button>
<span ng-show="correctAns">That is correct!</span>
<span ng-show="!correctAns">Sorry, that is an incorrect answer.</span>
JS:
var app = angular.module('quizApp', []);
app.directive('quiz', function (quizFactory) {
return {
restrict: 'AE',
scope: {},
templateUrl: 'template.html',
link: function (scope, elem, attrs) {
scope.start = function () {
scope.id = 0;
scope.quizOver = false;
scope.inProgress = true;
scope.getQuestion();
};
scope.reset = function () {
scope.inProgress = false;
scope.score = 0;
}
scope.getQuestion = function () {
var q = quizFactory.getQuestion(scope.id);
if (q) {
scope.question = q.question;
scope.options = q.options;
scope.answer = q.answer;
scope.answerMode = true;
} else {
scope.quizOver = true;
}
};
scope.checkAnswer = function () {
var ans = $('scope.myAnswer').val();
if(ans==scope.options[scope.answer]) {
scope.score++;
scope.correctAns = true;
} else {
scope.correctAns = false;
}
scope.answerMode = false;
};
scope.nextQuestion = function () {
scope.id++;
scope.getQuestion();
}
scope.reset();
}
}
});
app.factory('quizFactory', function () {
var questions = [
{
question: "Which of the following is a WW2 fighter?",
options: ["Albatross", "Concorde", "Spitfire", "Mirage"],
answer: 2
},
{
question: "When was the Great Fire of London?",
options: ["1666", "1966", "1844", "1235"],
answer: 0
},
{
question: "Which group is a Swedish pop band?",
options: ["Eagles", "Led Zeppelin", "Beatles", "Abba"],
answer: 3
},
{
question: "Which city is the capita of Australia?",
options: ["Canberra", "Sydney", "Melbourne", "Hobart"],
answer: 0
},
{
question: "Which brand does not make motorcycles?",
options: ["BMW", "Mercedes", "Kawasaki", "Honda"],
answer: 1
}
];
return {
getQuestion: function (id) {
if (id < questions.length) {
return questions[id];
} else {
return false;
}
}
};
});

directive that controlls upvotes and downvotes

I'm developing a upvote/downvote controlling system for a dynamic bunch of cards.
I can controll if I click to the img the checked = true and checked = false value but The problem I've found and because my code doesn't work as expected is I can't update my value in the ng-model, so the next time the function is called I receive the same value. As well, I can't update and show correctly the new value. As well, the only card that works is the first one (it's not dynamic)
All in which I've been working can be found in this plunk.
As a very new angular guy, I tried to investigate and read as much as possible but I'm not even 100% sure this is the right way, so I'm totally open for other ways of doing this, attending to performance and clean code. Here bellow I paste what I've actually achieved:
index.html
<card-interactions class="card-element" ng-repeat="element in myIndex.feed">
<label class="rating-upvote">
<input type="checkbox" ng-click="rate('upvote', u[element.id])" ng-true-value="1" ng-false-value="0" ng-model="u[element.id]" ng-init="element.user_actions.voted === 'upvoted' ? u[element.id] = 1 : u[element.id] = 0" />
<ng-include src="'upvote.svg'"></ng-include>
{{ element.upvotes + u[1] }}
</label>
<label class="rating-downvote">
<input type="checkbox" ng-click="rate('downvote', d[element.id])" ng-model="d[element.id]" ng-true-value="1" ng-false-value="0" ng-init="element.user_actions.voted === 'downvoted' ? d[element.id] = 1 : d[element.id] = 0" />
<ng-include src="'downvote.svg'"></ng-include>
{{ element.downvotes + d[1] }}
</label>
<hr>
</card-interactions>
index.js
'use strict';
var index = angular.module('app.index', ['index.factory']);
index.controller('indexController', ['indexFactory', function (indexFactory) {
var data = this;
data.functions = {
getFeed: function () {
indexFactory.getJSON(function (response) {
data.feed = response.index;
});
}
};
this.functions.getFeed();
}
]);
index.directive('cardInteractions', [ function () {
return {
restrict: 'E',
link: function (scope, element, attrs) {
scope.rate = function(action, value) {
var check_up = element.find('input')[0];
var check_down = element.find('input')[1];
if (action === 'upvote') {
if (check_down.checked === true) {
check_down.checked = false;
}
} else {
if (action === 'downvote') {
if (check_up.checked === true) {
check_up.checked = false;
}
}
}
}
}
};
}]);
Hope you guys can help me with this.
Every contribution is appreciated.
Thanks in advice.
I have updated your directive in this plunker,
https://plnkr.co/edit/HvcBv8XavnDZTlTeFntv?p=preview
index.directive('cardInteractions', [ function () {
return {
restrict: 'E',
scope: {
vote: '='
},
templateUrl: 'vote.html',
link: function (scope, element, attrs) {
scope.vote.upValue = scope.vote.downValue = 0;
if(scope.vote.user_actions.voted) {
switch(scope.vote.user_actions.voted) {
case 'upvoted':
scope.vote.upValue = 1;
break;
case 'downvoted':
scope.vote.downValue = 1;
break;
}
}
scope.upVote = function() {
if(scope.vote.downValue === 1) {
scope.vote.downValue = 0;
scope.vote.downvotes--;
}
if(scope.vote.upValue === 1) {
scope.vote.upvotes++;
} else {
scope.vote.upvotes--;
}
};
scope.downVote = function() {
if(scope.vote.upValue === 1) {
scope.vote.upValue = 0;
scope.vote.upvotes--;
}
if(scope.vote.downValue === 1) {
scope.vote.downvotes++;
} else {
scope.vote.downvotes--;
}
};
}
};

How can we disable other checkboxes by clicking a checkbox from a list in Angular2

I have an list of checkboxes. In this I want to disable other checkboxes When I have checked any item from list. Now if I uncheck that item then now all checkboxes need to be enabled.
This is the plunker - http://plnkr.co/edit/5FykLiZBQtQb2b31D9kE?p=preview
On unchecking any checkbox all the rest checkboxes are still disabled. How can I do this?
This is app.ts file -
import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core'
#Component({
selector: 'my-app',
template: `
<h2>{{title}}</h2>
<label *ngFor="let cb of checkboxes">
{{cb.label}}<input [disabled]="cb.status" type="checkbox"
[(ngModel)]="cb.state" (click)="buttonState(cb.id)">
</label><br />
{{debug}}
`
})
class App {
title = "Angular 2 - enable button based on checkboxes";
checkboxes = [{label: 'one',id: '0', status: ''},{label: 'two', id: '1', status:''},{label: 'three', id: '2', status: ''}];
constructor() {
//this.buttonState();
console.log("constructor called"); }
buttonState(id) {
console.log( id + "Button State Called");
//return this.checkboxes[0].status;
if(this.checkboxes[id].state == true){
this.checkboxes[id].status = true;
this.checkboxes[(id+1)%3].status = false;
this.checkboxes[(id+2)%3].status = false;
console.log("True Block");
}
else (this.checkboxes[id].state == false) {
this.checkboxes[id].status = false;
this.checkboxes[(id+1)%3].status = true;
this.checkboxes[(id+2)%3].status = true;
console.log("False Block");
}
}
get debug() {
return JSON.stringify(this.checkboxes);
}
}
bootstrap(App, [])
.catch(err => console.error(err));
Use this buttonState function instead yours:
buttonState(id) {
this.checkboxes.forEach(function(checkbox) {
if (checkbox.id !== id) {
checkbox.status = !checkbox.status;
}
})
}
see plunker example: http://plnkr.co/edit/ASzUR2jawpbifvwBXNO9?p=preview
another solution..not a good one...but still you can try it if you find any problem
class App {
title = "Angular 2 - enable button based on checkboxes";
checkboxes = [{label: 'one',id: '0', status: ''},{label: 'two', id: '1', status:''},{label: 'three', id: '2', status: ''}];
constructor() {
console.log("constructor called");
}
buttonState(id) {
console.log( this.checkboxes[id].state + "Button State Called");
//return this.checkboxes[0].status;
if(this.checkboxes[id].state == true ){
this.checkboxes[id].status = false;
this.checkboxes[(id+1)%3].status = false;
this.checkboxes[(id+2)%3].status = false;
console.log("True Block");
}
else if(this.checkboxes[id].state == false || this.checkboxes[id].state == undefined) {
this.checkboxes[id].status = false;
this.checkboxes[(id+1)%3].status = true;
this.checkboxes[(id+2)%3].status = true;
console.log("False Block");
}
}
http://plnkr.co/edit/mAvSQbyP9oh84LWfpGIm?p=preview

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;
});

how can i update the template view or json data so that i could re-render my template view in 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();
}
},

Resources