AngularJS - Manage button or input availability via model - angularjs

So, i'm quite stuck at this:
I have quite many buttons on my page, each button's availability is different in different context, for example:
When button "Add" is pressed, its state will be "disabled", Cancel and Save buttons will be available.
I came up with a solution to manage the stage of every buttons in one object call state, like this:
// This is the Controller
$scope.some_id = false;
// With some UI interaction, $scope.some_id will be some integer value
$scope.getContextBtnAdd = function(){ return $scope.some_id; };
$scope.getContextBtnCancel = function(){ return !$scope.getContextBtnAdd(); };
$scope.state = {
contextBtns : {
btnAdd : $scope.getContextBtnAdd(),
btnCancel: $scope.getContextBtnCancel(),
},
footerBtns : { Some footer buttons }
};
// This is the View
<button name="add" ng-disabled="!state.contextBtns.btnAdd">Add</button>
"So when there is no product load, $scope.some_id will be false, so Add button will be available, but when user clicks on some products, the $scope.some_id will be some integer value like 4,7 or 100... and the button will be disabled. " <=== That's what i want. But actually it doesn't work, the some_id changes but maybe the getContext function is never called. Right now i have to pass the getContext function to ng-disabled like this:
<button name="add" ng-disabled="!getContextBtnAdd()">Add</button>
But i want to manage them all via one object. So what's is my code problem and is there any better way to manage button, input....s availabilities?
Thank you!

When that line is executed:
$scope.state = {
contextBtns : {
btnAdd : $scope.getContextBtnAdd(),
btnCancel: $scope.getContextBtnCancel(),
},
footerBtns : { Some footer buttons }
};
the state object is created, and its contextBtns.btnAdd attribute (for example) takes the value returned by $scope.getContextBtnAdd() at that time. The attribute value never changes after.
What you want instead is something that always has the value of $scope.getContextBtnAdd() every time it's evaluated. So you simply need the function itself:
$scope.state = {
contextBtns : {
btnAdd : $scope.getContextBtnAdd,
btnCancel: $scope.getContextBtnCancel,
},
footerBtns : { Some footer buttons }
};
and in the view:
<button name="add" ng-disabled="!state.contextBtns.btnAdd()">Add</button>

Related

Show data in inputbox from 1 object and save it in using another object

I'm clicking a table row to edit the fields in a modal. The modal must have 2 functionalities (Add or Edit) depending on the GET request data like below.
$scope.editInterview = function(id) {
$http.get('/api/getinterview/' + id).then(function(response) {
editedObject = response.data.item
}
HTML
<label ng-if="editedObject.email">{{editedObject.email}}</label>
<label ng-if="!editedObject.email">Email</label>
<input ng-model="newObject.email" />
I am able to display the object in the labels, but that's not much help, because the data needs to be shown in the input boxes to be Edited and Saved.
How can i show the data from editedObject.email in the input, so i can save it using newObject.email?
I tried ng-init="editedObject.email", but it doesn't work. Is there some other ng-something that does this or i should be doing it in another way?
Update:
Edit and Update Methods, both are in the mainController.
$scope.editInterview = function(id) {
$http.get('/api/getinterview/' + id).then(function(response) {
editedObject = response.data.item
})
}
//Controller for the Modal
function DialogController($scope, $mdDialog, editedObject) {
$scope.editedObject = editedObject
$scope.submitObject = function(newObject) {
$http.post('/api/interview', newObject)
}
}
You have to make a deep copy from editObject.email to newObject.email. This could be done this way in controller after editOject.email has a value assigned.
$scope.newObject.email = angular.copy($scope.editObject.email);

Creating a "Like" button with Angular.js

Im trying to create a like button with Angular.js.
(It is just a heart icon. default color is white = NOT liked. It is red when liked. Like/unlike is toggled by a click)
I get some data from my web service that has also an array of some ID's. These ID's are the ones that clicked the like button before.
Then i populate the DOM with the ng-repeat directive according to the data retrieved from the web service.
I attach the button a ng-class that sets the proper class and a ng-click directive that is supposed to somehow change the class too.
* I cant connect between the ng-class and the ng-click result.
some code:
<div ng-repeat="photo in photos track by photo._id">
<button ng-class="{carouselFooterButtonLikeActive : initLike(photo)}" ng-click="like(photo, this)">
<i class="icon ion-heart"></i>
</button>
</div>
Controller:
// Handle like button click
$scope.like = function(photo, photoScope){
HOW CAN I AFFECT THE NG-CLASS FROM HERE?
}
$scope.initLike = function(photo){
if(photo.likes.indexOf($localstorage.getObject('userInfo').id) > -1) {
$scope.liked = true;
return true;
}
$scope.liked = false;
return false;
}
Edit: added a possible data retrieved from the web service
{
photos: [
{
src: "src1.jpg",
likes:[111,222,333]
},
{
src: "src2.jpg",
likes:[]
}
]
}
You can use as a flag some additional property that will be initially undefined on each photo element - say photo.liked. When user clicks it, $scope.like function sets this property to true. Then ng-class evaluates photo.liked to true and adds carouselFooterButtonLikeActive class to button element.
The code is as follows:
In the template:
<button ng-class="{'carouselFooterButtonLikeActive' : photo.liked}" ng-click="like(photo, this)">
In the controller:
$scope.like = function(photo, photoScope){
photo.liked = true;
}
UPD
Say you have photos array:
[
{'src':'bla-bla.jpg', liked: true, id: 8347},
{'src':'foo-bar.jpg', id: 45},
{'src':'baz-baz.jpg', id: 47}
]
then only the first one will be shown with button.carouselFooterButtonLikeActive class, thanks to ng-class evaluation expression.
UPD2
If photo.likes is an array, you can use:
//template
ng-class="{'carouselFooterButtonLikeActive' : (photo.likes && photo.likes.length >0)}"
//controller
$scope.like = function(photo, photoScope){
photo.likes.push(someUserID);
}

angularjs : disable a button and show popup instead

I have this button :
html:
<button nav-direction="back" class="button yy" ui-sref="app.result" ui-sref-active="currentNav" ng-click="navResult()">
Board
</button>
I would like it to display a popup if a certain condition is, else I would like it to go to another page.
I need to keep the benefit of the class in ui-sref-active to show that this is the current page.
controller.js
$scope.navResult = function (){
console.log(sessionService.get('computed'));
if (sessionService.get('computed')) {
$scope.go('app.result');
} else {
//popup to user to tap on a board
//$scope.go('app.compute');
var popupConfig = {
title: 'Beware! ;)',
template: 'Tap on a board below'
};
var popup = $ionicPopup.show(popupConfig);
ClosePopupService.register(popup);
}
}
$scope.go = function ( state ) {
// console.log("go has been launched with : "+ state)
$state.go( state );
};
Simple. You just use an ng-click method instead of a ui-sref, and go to the state from there.
<button nav-direction="back" ng-class="{'your-class':classCondition}" class="button yy" ng-click="navResult()">
Board
</button>
Then in your controller....
$scope.navResult = function(){
if(something){
$scope.classCondition = false;
//code to display popup here
} else {
$state.go('app.result')
}
}
You can pass any valid state into $state.go, so if you ever want to check for a condition and perform some logic BEFORE you redirect to another page, use it inside a $scope method instead of just using the straight ui-sref.

ExtJS 4.1: Modal Window seems to return control before submitting the window

I wasn't sure how to describe my question in the question title. But here is my problem:
(a) When I double click on a row in an Ext.grid.Panel, I open a modal window with it's relavant details to update the record.
(b) After I make the needed modifications and close the modal window, I want to return to the Grid with the Grid filtered on a certain code i.e selectedSalesOrderNum.
jobSlotsGrid.on('celldblclick', function(tableview, td, cellIndex, record, tr, rowIndex, e, eOpts){
modalStatus = loadWindow();
jobSlotStore.filterBy(function(rec) {
alert('Filtering data');
return rec.get('salesOrderNum') === selectedSalesOrderNum;
});
});
(c) Below is the function, which creates the model window. It also has the call to method submitCreateJobSlotHandler() which basically saves the changes and reloads the original Grid with all the data. ( Hence the necessity to filter it back with a certain code i.e selectedSalesOrderNum ).
function loadWindow()
{
getAllTabsForEditJobSlot();
var createJobSlotWin = new Ext.Window({
id:'salesOrder-win-jobSlot',
applyTo : 'hello-win',
modal : true,
layout : 'fit',
width : 900,
height : 500,
closeAction :'destroy',
plain : true,
model : true,
stateful : false,
title :'Create Job Slot',
items : [editJobSlotInformationPanel],
buttons : [{
text : 'Save',
handler : function(){
submitCreateJobSlotHandler();
//createJobSlotWin.destroy();
}
},{
text : 'Close',
handler : function(){
createJobSlotWin.destroy();
}
}]
});
createJobSlotWin.show();
}
The Issue:
In the first block of code, as soon as the loadWindow method is called, both a modal window is popped up along with the filterBy code getting executed in parallel and showing up the alerts ( 'Filtering data' ). I then enter the data in the modal and save. So, basically, the filtering is not done after the Save/Close on Modal. The code ( if/else ) is immediately reached after loading the modal window. It is as if, the modal window opens and goes to the next line of code while waiting for the user to perform some action on the modal window later.
Hope I am clear on my question. Could anyone please advice how do I handle this?
EDIT:
The more I think about it now, I guess the loadWindow() method just creates the Modal Window as we just have a new Ext.Window() call and doesn't bother about other user actions inside the modal and returns the control. And hence, executes the subsequent filterBy event immediately. In that case, I want to filter the store after I am reloading the store upon the Save in Modal Window. The save on Modal window has this handler code:
function submitCreateJobSlotHandler () {
alert('Into Submit');
var formPanel = Ext.getCmp('salesOrderJobSlotForm');
formPanel.getForm().submit({
url : 'someUrl',
method : 'POST',
success : function() {
alert('Success');
jobSlotStore.load({
scope : this,
url : 'salesOrderJobSlot/listJSON'
});
jobSlotStore.filterBy(function(rec) {
alert(rec.get('salesOrderNum')+"--"+selectedSalesOrderNum)
return rec.get('salesOrderNum') === selectedSalesOrderNum;
});
},
failure : function() {
alert('PSO save failed!');
}
});
}
But the issue here is, the jobSlotStore.load() though gets called, it holds until the filterBy gets executed. Because, I see the alerts coming up one by one and then after all the alerts are done, the store loads. So, the filterBy gets overriden by the 'late' store load.
Any suggestions to deal with the issue in any of the ways?
The store load is asynchronous, you need to wait til it completes before you can filter the data set on the client:
store.on('load', function() {
store.filter();
}, null, {single: true});
store.load();

Add class to DIV if checkbox is checked onload

I need help with a script to add an "active" class to a div when a hidden checkbox is checked. This all happening within a somewhat complex form that can be saved and later edited. Here's the process:
I have a series of hidden checkboxes that are checked when a visible DIV is clicked. Thanks to a few people, especially Dimitar Christoff from previous posts here, I have a few simple scripts that handle everything:
A person clicks on a div:
<div class="thumb left prodata" data-id="7"> yadda yadda </div>
An active class is added to the div:
$$('.thumb').addEvent('click', function(){
this.toggleClass('tactive');
});
The corresponding checkbox is checked:
document.getElements("a.add_app").addEvents({
click: function(e) {
if (e.target.get("tag") != 'input') {
var checkbox = document.id("field_select_p" + this.get("data-id"));
checkbox.set("checked", !checkbox.get("checked"));
}
}
});
Now, I need a fourth ( and final ) function to complete the project (using mootools or just plain javascript, no jQuery). When the form is loaded after being saved, I need a way to add the active class back to the corresponding div. Basically reverse the process. I AM trying to figure it out myself, and would love to post an idea but anything I've tried is, well, bad. I thought I'd at least get this question posted while I work on it. Thanks in advance!
window.addEvents({
load: function(){
if (checkbox.checked){
document.getElements('.thumb').fireEvent('click');
}
}
});
Example: http://jsfiddle.net/vCH9n/
Okay, in case anyone is interested, here is the final solution. What this does is: Create a click event for a DIV class to toggle an active class onclick, and also correlates each DIV to a checkbox using a data-id="X" that = the checkbox ID. Finally, if the form is reloaded ( in this case the form can be saved and edited later ) the final piece of javascript then sees what checkboxes are checked on page load and triggers the active class for the DIV.
To see it all in action, check it out here: https://www.worklabs.ca/2/add-new/add-new?itemetype=website ( script is currently working on the third tab, CHOOSE STYLE ). You won't be able to save/edit it unless you're a member however, but it works:) You can unhide the checkboxes using firebug and toggle the checkboxes yourself to see.
window.addEvent('domready', function() {
// apply the psuedo event to some elements
$$('.thumb').addEvent('click', function() {
this.toggleClass('tactive');
});
$$('.cbox').addEvent('click', function() {
var checkboxes= $$('.cbox');
for(i=1; i<=checkboxes.length; i++){
if(checkboxes[i-1].checked){
if($('c_'+checkboxes[i-1].id))
$('c_'+checkboxes[i-1].id).set("class", "thumb tactive");
}
else{
if($('c_'+checkboxes[i-1].id))
$('c_'+checkboxes[i-1].id).set("class", "thumb");
}
}
});
// Add the active class to the corresponding div when a checkbox is checked onLoad... basic idea:
var checkboxes= $$('.cbox');
for(i=1; i<=checkboxes.length; i++){
if(checkboxes[i-1].checked){
$('c_field_tmp_'+i).set("class", "thumb tactive");
}
}
document.getElements("div.thumb").addEvents({
click: function(e) {
if (e.target.get("tag") != 'input') {
var checkbox = document.id("field_tmp_" + this.get("data-id"));
checkbox.set("checked", !checkbox.get("checked"));
}
}
});
});

Resources