how to collapse all function on for each angular UI tree - angularjs

For Angular ui-tree, i want to add expland all or collapse all.
I tried the following code and it works.
$scope.collapseAll = function () {
$scope.$broadcast('angular-ui-tree:collapse-all');
};
$scope.expandAll = function () {
$scope.$broadcast('angular-ui-tree:expand-all');
};
...
The question is,my page have multiple ui tree, i only want to trigger expandAll function for separate. now i trigger this expandAll function. ALL ui -tree will be affected.
Is there any solution to set each one as seperate?
How to call collapseAll function on Angular UI tree?

If you check at the Source of angular ui tree , the 'angular-ui-tree:collapse-all' event toggles a scope value . Other problem being each of the directives in angular-ui-tree inherits the scope of the parent than having a isolated scope . So changing the when you broadcast an event it is actually changing the same scope value .
You should either find a way for each tree's to have a separate scope or think of using some other tree's like v-accordion .

we should broadcast angular-ui-tree:collapse-all for specified tree scope.
It's work for me.you can use it without any hesitation at all.
function collapseAll() {
var treeScope = _getRootNodesScope('myTreeId');
if (treeScope) {
treeScope.$broadcast('angular-ui-tree:collapse-all');
}
}
function expandAll() {
var treeScope = _getRootNodesScope('userTreeroot');
if (treeScope) {
treeScope.$broadcast('angular-ui-tree:expand-all');
}
}
function _getRootNodesScope(myTreeId) {
var treeElement = angular.element(document.getElementById(myTreeId));
if (treeElement) {
var treeScope = (typeof treeElement.scope === 'function') ?
treeElement.scope() : undefined;
return treeScope;
}
return undefined;
};

Related

ExtJS how to effetively store values common for several functions in a single controller

In view I have 4 buttons. In controller I have references to those buttons. There is the complicated logic to enable/disable each button, unfortunatelly scattered into several function - event listeners. Each listener has different parameters. Example:
listener1: function(data1) {
button1.setDisabled(data1.status = ProcessStatus.running);
button2.setDisabled(data1.status = ProcessStatus.running);
}
listener2: function(upload) {
button2.setDisabled(!upload.enabled);
}
I want to refactor the code: create single function in controller updateButtonsState. Then each listener would set somewhere a value and call updateButtonsState() without parameters.
listener2: function(upload) {
saveUploadEnabled(upload.enabled);
updateButtonsState();
button2.setDisabled(!upload.enabled);
}
updateButtonsState: function() {
var uploadEnabled = loadUploadEnabled();
var data1StatusProcessRunning = loadData1Status();
button1.setDisabled(data1StatusProcessRunning);
button2.setDisabled(uploadEnabled || data1StatusProcessRunning);
}
How to implement save* and load* methods? Where should I store those data?
Two major possibilities: You can store the state directly in the controller, or use a closure to create a "private" variable and not expose it to anything except the getter/setter functions that are your interface.
controllers have an init method that you could use for the closure:
init: function(application) {
var myPrivateVariable = {};
this.saveUploadEnabled = function(uploadEnabled) {
myPrivateVariable.uploadEnabled = uploadEnabled;
}
this.saveStatus = function(status) {
myPrivateVariable.status = status;
}
this.updateButtonState = function() {
button1.setDisabled(myPrivateVariable.status == ProcessStatus.Running || !myPrivateVariable.uploadEnabled)
}
}

Create and destroy Angular watchers

I would like to turn off this watcher because it keeps hitting "kendoWidgetCreated" event over and over again, and causes an infinite loop where I hit the kendoGrid.refresh() .
How can I turn it off, then turn back on ?
scope.$on("kendoWidgetCreated", function (ev, widget) {
var kendoGrid = widget.element.parent().find('.k-grid').data("kendoGrid");
if (kendoGrid != undefined) {
kendoGrid.$angular_scope.compileTemplate();
kendoGrid.refresh();
}
});
I tried something like this, but couldn't get the watcher to trigger :
var kendoWidgetWatcher = scope.$watch("kendoWidgetCreated", refreshKendoWidgets);
var refreshKendoWidgets = function (ev, widget) {
// widget compile/refresh code here...
}
Advice is always appreciated...
regards,
Bob
***** UPDATE ****
My initial idea for creating an anonymous function was NOT working; however, Pankar's answer below worked for me.
Here's the updated, working version :
// setup new 'kendoWidgetWatcher' object for Kendo widget watcher, compile/refresh Kendo grids/charts
var kendoWidgetWatcher;
function registerWatcher() {
kendoWidgetWatcher = scope.$on("kendoWidgetCreated", refreshKendoWidgets);
}
function refreshKendoWidgets(ev, widget) {
var ht = widget.getSize().height;
var wt = widget.getSize().width;
var kendoGrid = widget.element.parent().find('.k-grid').data("kendoGrid");
if (kendoGrid != undefined) {
if (kendoWidgetWatcher) {
kendoWidgetWatcher(); // disable watch
}
kendoGrid.$angular_scope.compileTemplate(); // recompile the html tempate, then refresh kendo widget
kendoGrid.refresh();
registerWatcher(); // re-enable
}
}
You could easily turn off your your watcher by calling the watcher reference as function, and re-register it whenever you want it.
var kendoWidgetWatcher;
function refreshKendoWidgets(ev, widget) {
var kendoGrid = widget.element.parent().find('.k-grid').data("kendoGrid");
if (kendoGrid != undefined) {
kendoGrid.$angular_scope.compileTemplate();
kendoGrid.refresh();
// HOW TO DISABLE THE WATCH HERE ?
}
}
function registerWatcher (){
kendoWidgetWatcher = scope.$watch("kendoWidgetCreated", refreshKendoWidgets);
}
registerWatcher();
//you could call below code for re-registering the watcher
if(kendoWidgetWatcher)
kendoWidgetWatcher(); //to deregister it.
registerWatcher(); //re-register it.

angularjs with ace code editor - forcing the editor to execute 'onblur' when model changes

I am using angularjs in conjunction with ui-ace, a library that has a directive for the popular ace library.
ui-ace
ace text editor
I have made some modifications to the directive because I need it to work with string[], instead of normal strings. Everything works fine except a strange situation when switching my core model. Here is how it is set up;
There is a grid with objects from my database.
When an item in the grid is clicked, the $scope.Model is populated with the information from the database
This includes a property called Scripting, which is a string[], and it is bound to the ace text editor.
the editor's text is set to $scope.Model.Scripting.join('\n')
this behavior is repeated in different ways in the editor's onChange and onBlur events.
Now, what is going wrong is that I have to actually click on the text editor to trigger the onBlur event before I click on an item in the grid. This has to be repeated each time, or the editor won't update. I cannot figure out why this is happening.
Here is the relevant code. I am going to link the whole directive, as well. The plunkr has everything needed to reproduce the issue, including exact instructions on how to do so.
Full Demonstration and Full Directive Live (Plunkr)
Relevant Directive Changes
return {
restrict: 'EA',
require: '?ngModel',
priority: 1,
link: function (scope, elm, attrs, ngModel) {
/**
* Corresponds to the ngModel, and will enable
* support for binding to an array of strings.
*/
var lines = scope.$eval(attrs.ngModel);
/*************************************************
* normal ui-ace code
************************************************/
/**
* Listener factory. Until now only change listeners can be created.
* #type object
*/
var listenerFactory = {
/**
* Creates a blur listener which propagates the editor session
* to the callback from the user option onBlur. It might be
* exchanged during runtime, if this happens the old listener
* will be unbound.
*
* #param callback callback function defined in the user options
* #see onBlurListener
*/
onBlur: function (callback) {
return function (e) {
if (angular.isArray(lines)) {
scope.$apply(function () {
ngModel.$setViewValue(acee.getSession().doc.$lines);
});
}
executeUserCallback(callback, acee);
};
}
};
// Value Blind
if (angular.isDefined(ngModel)) {
ngModel.$formatters.push(function (value) {
if (angular.isUndefined(value) || value === null) {
return '';
}
else if (angular.isArray(value)) {
return '';
}
// removed error if the editor is bound to array
else if (angular.isObject(value)) {
throw new Error('ui-ace cannot use an object as a model');
}
return value;
});
ngModel.$render = function () {
if (angular.isArray(lines)) {
session.setValue(scope.$eval(attrs.ngModel).join('\n'));
}
else {
// normal ui-ace $render behavior
}
};
}
// set the value when the directive first runs.
if (angular.isArray(lines)) {
ngModel.$setViewValue(acee.getSession().doc.$lines);
}
Looks like you set up ngModel.$formatters incorrectly for your array case.
Try changing:
else if (angular.isArray(value)) {
return '';
}
To:
else if (angular.isArray(value)) {
return value.join('');
}
Personally I think it would have been easier to pass joined arrays in to model and not modify the directive. Then you wouldn't have issues with future upgrades
DEMO

BackboneJS - same el for many views

I am using same el for more than 1 view like below. I'm not facing any problem till now. Is this good approach or should i do any changes?
<div id="app">
<div id="app-header"></div>
<div id="app-container"></div>
<div id="app-footer">
</div>
App View:
{
el: "#app",
v1: new View1(),
v2: new View2(),
render: function () {
if (cond1) {
this.v1.render();
} else if (cond2) {
this.v2.render();
}}
}
View 1:
{
el: "#app-container",
render: function (){
this.$el.html(template);
}
}
View 2:
{
el: "#app-container",
render: function (){
this.$el.html(template);
}
}
By reading your question, I do not really see what advantages you could possibly have using this approach rather than having the different div elements being the root el for your views 1, 2, 3 and using
this.$el.html(template)
in the render method.
Your approach could work for a small application, but I think it will become really hard to maintain as the application grows.
EDIT
I still do not really get your point, you could only initialize everything only once in both cases.
Here is a working Fiddle.
By the way I am changing the content by listening to the click event but this is to simplify the example. It should be done by the router.
I do use a mixin to handle such situation, I call it stated view. For a view with all other options I will send a parameter called 'state', render will in-turn call renderState first time and there after every time I set a 'state' renderState will update the view state. Here is my mixin code looks like.
var setupStateEvents = function (context) {
var stateConfigs = context.getOption('states');
if (!stateConfigs) {
return;
}
var state;
var statedView;
var cleanUpState = function () {
if (statedView) {
statedView.remove();
}
};
var renderState = function (StateView) {
statedView = util.createView({
View: StateView,
model: context.model,
parentEl: context.$('.state-view'),
parentView:context
});
};
context.setState = function (toState) {
if (typeof toState === 'string') {
if (state === toState) {
return;
}
state = toState;
var StateView = stateConfigs[toState];
if (StateView) {
cleanUpState();
renderState(StateView);
} else {
throw new Error('Invalid State');
}
} else {
throw new Error('state should be a string');
}
};
context.getState = function () {
return state;
};
context.removeReferences(function(){
stateConfigs = null;
state=null;
statedView=null;
context=null;
})
};
full code can be seen here
https://github.com/ravihamsa/baseapp/blob/master/js/base/view.js
hope this helps
Backbone Rule:
When you create an instance of a view, it'll bind all events to el if
it was assigned, else view creates and assigns an empty div as el for that view and bind
all events to that view.
In my case, if i assign #app-container to view 1 and view 2 as el and when i initialize both views like below in App View, all events bind to the same container (i.e #app-container)
this.v1 = new App.View1();
this.v2 = new App.View2();
Will it lead to any memory leaks / Zombies?
No way. No way. Because ultimately you are having only one instance for each view. So this won't cause any memory leaks.
Where does it become problematic?
When your app grows, it is very common to use same id for a tag in both views. For example, you may have button with an id btn-save in both view's template. So when you bind btn-save in both views and when you click button in any one the view, it will trigger both views save method.
See this jsFiddle. This'll explain this case.
Can i use same el for both view?
It is up to you. If you avoid binding events based on same id or class name in both views, you won't have any problem. But you can avoid using same id but it's so complex to avoid same class names in both views.
So for me, it looks #Daniel Perez answer is more promising. So i'm going to use his approach.

wait for backbone template to be appended to the dom

I am trying to bind events to elements that are placed by appending a backbone template:
appendEditTemplateAndSetEvents: function() {
var associatedCollection = App.Helpers.findAssociatedCollection(this.allCollections, this.associatedCollectionId);
var template = this.setEditTemplateForElement(associatedCollection.type);
var modalBody = this.$el.find('.modal-body');
modalBody.empty();
var firstModel = associatedCollection.at(0);
if(template.mainTemplate !== null) {
modalBody.append($('#edit-form-element-frame').html());
//each mode in collection
associatedCollection.each(function(model){
if(model.get('positionInContainer') === 1) {
firstModel = model;
}
console.log(model.attributes);
modalBody.find('.elements-in-editmodal-wrapper').append(template.mainTemplate(model.toJSON()));
});
}
if( template.templateValidation.length !== 0 ) {
modalBody.append('<hr><h3>Validateregels</h3>');
_.each(template.templateValidation, function(val, index) {
modalBody.append(val(firstModel.toJSON()));
});
}
//set listeners and handlers that apply when a edit modal is open
this.validationEventsForEditModal(firstModel);
this.editErrorMessagesInModal(firstModel);
},
Now the problem is that when the last two functions are called the html of the templates isn't appended yet so the the events are binded to an object with a length of 0.
Does anyone have a decent solution for this async problem? I tried $.Defferred but that did not work, but maybe someone get's it working.
I solved this by using this.$el.find(...) in the functions:
this.validationEventsForEditModal(firstModel);
this.editErrorMessagesInModal(firstModel);
I don't know if it's still an async problem, but this solves it.

Resources