Re-binding a tree (Wijmo tree) with AngularJS - angularjs

I am fairly new to AngularJS, and really struggling to re-bind a Wijmo tree (or even a tree implemented using UL and LI elements wth ng-repeat) with new data on changing of value of a Wijmo combobox (or, even a regular dropdown of HTML select elem).
Below is the code I have written, which is working fine in initial page load. But on changing the dropwdown, the tree is not being reloaded with new data fetched by loadDomainTree method; it is still showing old data. Can somebody help me figure out what's wrong with this code?
HTML:
<div ng-controller="DomainCtrl">
<select id="domain" ng-model="currentDomain" ng-options="item.Name for item in domainList"></select>
<div>
<ul id="wijtree">
<li ng-repeat="item in domainEntityList" id={{item.Id}}>
<a>{{item.Name}}</a>
</li>
</ul>
</div>
</div>
JS:
$(document).ready(function ()
{
$("#domain").wijcombobox({
isEditable: false
});
$("#wijtree").wijtree();
});
function DomainDropdownModel(data) {
this.Id = data.Id.toString();
this.Name = data.Name;
};
function DomainTreeModel(data) {
this.Id = data.Id;
this.Name = data.Name;
};
function DomainCtrl($scope, $locale) {
$scope.domainList = [];
$.ajax({
url: dropDownUrl,
async: false,
success: function (data) {
$(data).each(function (i, val) {
var domain = data[i];
var domainId = domain.Id.toString();
var domainName = domain.Name;
$scope.domainList.push(new DomainDropdownModel({ Id: domainId, Name: domainName }));
});
}
});
$scope.currentDomain = $scope.domainList[0];
$scope.loadDomainTree = function (domainId) {
domainEntitiesUrl = DOMAIN_API_URL + DOMAIN_ID_PARAM + domainId;
//alert(domainEntitiesUrl);
$scope.domainEntityList = [];
$.ajax({
url: domainEntitiesUrl,
async: false,
success: function (data) {
$(data).each(function (i, entity) {
var domainEntity = data[i];
var domainEntityId = domainEntity.Id.toString();
var domainEntityName = domainEntity.Name;
$scope.domainEntityList.push(new DomainTreeModel({ Id: domainEntityId, Name: domainEntityName }));
});
}
});
};
//Will be called on setting combobox dfault selection and on changing the combobox
$scope.$watch('currentDomain', function () {
$scope.loadDomainTree($scope.currentDomain.Id);
});
}

You may $watch for the selectedItem of WijCombobox and then, re-load the wijtree accordingly. Here is the code:
$scope.$watch('selectedItem', function (args) {
if (args === 'Tree 1') {
$("#wijtree").wijtree("option", "nodes", $scope.nodes1);
}
else {
$("#wijtree").wijtree("option", "nodes", $scope.nodes2);
}
});
HTML Code
<wij-combobox data-source="treeList" selected-value="selectedItem">
<data>
<label bind="name"></label>
<value bind="code"></value>
</data>
</wij-combobox>

Related

Kendo treeview expands on initialization not working

I'm trying to expand Kendo treeview all nodes on initialization.
But is not working. Here are solutions I have referenced:
1.http://dojo.telerik.com/UqOxa/2
2.http://www.telerik.com/forums/how-do-you-default-a-treeview-to-expanded-on-initialization
My source code:
html:
<div id="kendoTreeViewSelector"
kendo-tree-view="tree"
k-data-source="treeData"
k-on-change="selectedItem = dataItem"
k-on-data-bound="onDataBound"
ng-click="kendoTreeViewToggle($event)">
<span k-template>
{{dataItem.text}}
</span>
</div>
Angular controller:
ServiceMenusRepository.getMenus(data.EmployeeNO, 2, selectType, SystemSN,
function (data) {
if (data.data) {
$scope.treeData = new kendo.data.HierarchicalDataSource({
data: data.data,
});
$scope.subMenuItems = data.data;
$scope.onDataBound = function (e) {
setTimeout(function () {
$scope.tree.expand(".k-item");;
});
}
$scope.kendoTreeViewToggle = function (e) {
var target = $(e.target);
var toggleIcon = target.closest(".k-icon");
if (!toggleIcon.length) {
this.tree.toggle(target.closest(".k-item"));
}
};
$timeout(function () {
initMenu();
menu2q.resolve();
}, 0);
} else {
menu2q.resolve();
}
}, menuq.reject);
By the way, I'm using Kendo UI v2015.1.429.
Is there any suggestion for this problem?
Many thanks!!
In the dataBound event of the TreeView, try:
e.sender.expand(".k-item");
It's from the demo at http://demos.telerik.com/kendo-ui/dialog/treeview-integration. I just used it yesterday and my tree is all expanded.
You can also try adding an expanded: true field to the items in data.data as this demo does when it sets the data for its HierarchicalDataSource: http://demos.telerik.com/kendo-ui/treeview/filter-treeview-in-dialog

AngularJS $http.get function not executed second time

I have a requirement to create a multiselect dropdown using angularjs with values coming from database based on different parameters.I have implemented following code. It is working fine when the page loads at first time. If come to this page second time, the $http.get function is not executing and still showing the same data as in the first page load.
This is my .js file:
var app = angular.module("myModule", ["angularjs-dropdown-multiselect"]);
app.controller("myController", ['$scope','$http', function ($scope,$http) {
$scope.AllDescriptions = [];
$scope.DescriptionsSelected = [];
$scope.dropdownSetting = {
scrollable: true,
scrollableHeight: '200px'
};
$http.get('/Areaname/ControllerName/MethodName').then(function (data) {
angular.forEach(data.data, function (value, index) {
$scope.AllDescriptions.push({ id: value, label: value });
});
});
}])
This is my html file :
<div ng-app="myModule" ng-controller="myController" >
<div class="container">
<div id="divRight" style="min-height:5px;display: inline-block; width: 40%; vertical-align: top;">
<label style="float:left;">Error Description : </label>
<div style="float:left;width:200px;margin-left:10px" ng-dropdown-multiselect="" extra-settings="dropdownSetting" options="AllDescriptions" selected-model="DescriptionsSelected" checkboxes="true"></div>
</div>
</div>
</div>
This is my .cs file :
public JsonResult MethodName()
{
List<string> errorDescriptions = //Get from server
return new JsonResult() { Data=errorDescriptions,JsonRequestBehavior=JsonRequestBehavior.AllowGet};
}
Kindly help me to execute this JSON method for every page request instead of only in the first page request. Thank you.
I think the problem is with cache. Try to put your get method in variable ($scope.GetDescriptions = function () { $http.get... }) and use ng-init directive
(<div class="container" ng-init="GetDescriptions()">). Also try to empty array before push elements in it ($scope.AllDescriptions = [], $scope.AllDescriptions.push(...)
Try adding $route.reload(), this reinitialise the controllers but not the services:
app.controller("myController", ['$scope','$http','$route' function ($scope,$http,$route) {
$route.reload(); // try pass parameter true to force
$scope.AllDescriptions = [];
$scope.DescriptionsSelected = [];
$scope.dropdownSetting = {
scrollable: true,
scrollableHeight: '200px'
};
$http.get('/Areaname/ControllerName/MethodName').then(function (data) {
angular.forEach(data.data, function (value, index) {
$scope.AllDescriptions.push({ id: value, label: value });
});
});
}])
If you want to reset the whole state of your application you can use $window.location.reload(); instead route like:
app.controller("myController", ['$scope','$http','$route' function ($scope,$http,$route) {
$window.location.reload(); // try pass parameter true to force
$scope.AllDescriptions = [];
$scope.DescriptionsSelected = [];
$scope.dropdownSetting = {
scrollable: true,
scrollableHeight: '200px'
};
$http.get('/Areaname/ControllerName/MethodName').then(function (data) {
angular.forEach(data.data, function (value, index) {
$scope.AllDescriptions.push({ id: value, label: value });
});
});
}])
Hope this works.

ng-click event binding not working inside angular-datatables

I am using angular-datatables for listing student information. I want to implement server-side ajax implementation for every search, sorting, paging etc rather than fetch all data and repeat the data using angularjs. sorting, searching, paging is working fine. But I am unable to bind ng-click event when click on specific row actions.
This is my view:
This is my javascript source code:
<div ng-app="myApp">
<div ng-controller="OrganizationController">
<table id="entry-grid" datatable="" dt-options="dtOptions"
dt-columns="dtColumns" class="table table-hover"></table>
</div>
</div>
<script>
var app = angular.module('myApp',['datatables']);
app.controller('OrganizationController', BindAngularDirectiveCtrl);
function BindAngularDirectiveCtrl($scope, $compile, DTOptionsBuilder, DTColumnBuilder) {
var vm = this;
vm.message = '';
vm.edit = edit;
vm.dtInstance = {};
vm.persons = {};
$scope.dtColumns = [
DTColumnBuilder.newColumn("organization_name").withOption('organization_name'),
DTColumnBuilder.newColumn(null).withTitle('Actions').notSortable()
.renderWith(actionsHtml)
]
$scope.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
dataSrc: "data",
url: "organizations",
type:"get"
})
.withOption('processing', true) //for show progress bar
.withOption('serverSide', true) // for server side processing
.withPaginationType('full_numbers') // for get full pagination options // first / last / prev / next and page numbers
.withDisplayLength(2) // Page size
.withOption('aaSorting',[0,'asc'])
function edit() {
console.log('hi')
}
function actionsHtml(data, type, full, meta) {
vm.persons[data.id] = data;
return '<button class="btn btn-warning" ng-click="edit()">' +
' <i class="fa fa-edit"></i>' +
'</button>';
}
}
</script>
You didn't add withOption("rowCallback",fn)
<script>
var app = angular.module('myApp',['datatables']);
app.controller('OrganizationController', BindAngularDirectiveCtrl);
function BindAngularDirectiveCtrl($scope, $compile, DTOptionsBuilder, DTColumnBuilder) {
var vm = this;
vm.message = '';
vm.edit = edit;
vm.dtInstance = {};
vm.persons = {};
$scope.dtColumns = [
DTColumnBuilder.newColumn("organization_name").withOption('organization_name'),
DTColumnBuilder.newColumn(null).withTitle('Actions').notSortable()
.renderWith(actionsHtml)
]
$scope.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
dataSrc: "data",
url: "organizations",
type:"get"
})
.withOption('rowCallback', rowCallback)
.withOption('processing', true) //for show progress bar
.withOption('serverSide', true) // for server side processing
.withPaginationType('full_numbers') // for get full pagination options // first / last / prev / next and page numbers
.withDisplayLength(2) // Page size
.withOption('aaSorting',[0,'asc'])
function edit() {
console.log('hi')
}
function actionsHtml(data, type, full, meta) {
vm.persons[data.id] = data;
return '<button class="btn btn-warning" ng-click="edit()">' +
' <i class="fa fa-edit"></i>' +
'</button>';
}
function rowCallback(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
// Unbind first in order to avoid any duplicate handler (see https://github.com/l-lin/angular-datatables/issues/87)
$('td', nRow).unbind('click');
$('td', nRow).bind('click', function()
{
$scope.$apply(function() {
alert("You've clicked row," + iDisplayIndex);
});
});
return nRow;
}
}
</script>
If we want to bind a click event to specific DOM element in angular datatable row find(jQuery)that element using any CSS selector. For example -
HTML
<table id='table' datatable [dtOptions]="dtOptions" class="table table-sm table-striped table-bordered" cellspacing="0" width="100%">
Angular(v4) Component-
export class ExampleComponent implements OnInit {
dtOptions: DataTables.Settings = {};
ngOnInit() {
//Starts Angular jQuery DataTable server side processing settings
let ajaxSettings: any = {
settings: {
ajax: {
...
},
serverSide: true,
searchDelay: 800,
deferRender: true,
processing: true,
autoWidth: false,
stateSave: false,
searching: true,
aoColumns: [
//Table column definition
{
//Action Column
sTitle: 'Action',
sWidth: "20%",
bSearchable: false,
bSortable: false,
mRender: (data, type, full) => {
return "<a href='javascript:void(0);' class='custombtn btn btn-sm btn-primary'><span class='fa fa-paper-plane-o'></span>Action Button</a>";
}
}
],
fnServerParams: function (data) {
},
initComplete: () => {
},
rowCallback: (row: Node, data: any[] | Object, index: number) => {
const self = this;
// Unbind first in order to avoid any duplicate handler
// (see https://github.com/l-lin/angular-datatables/issues/87)
var element = $('td', row).find('a.custombtn');
if (element) {
element.unbind('click');
element.bind('click', () => {
self.someClickHandler(data, index);
});
}
return row;
}
}
};
this.dtOptions = ajaxSettings.settings;
//Ends Angular jQuery DataTable server side processing settings
}
//Will be called on click of anchor tag which has the class "custombtn"
someClickHandler(info: any, index: number): void {
alert(JSON.stringify(info) + ' index =>' + index);
}
}

AngularJS and UI-Router: keep controller loaded

I am building a web application for our customer support. One of the needs is to be able to keep multiple tickets opened at the same time.
I was able to do the first part easily using a tabulation system and UI-Router.
However, with my current implementation, each time I change active tab, the previously-current tab is unloaded, and the now-current tab is loaded (because it was unloaded with a previous tab change).
This is not at all the expected behavior. I've already spent a couple of days trying to find a way to achieve this, without any luck.
The closest thing I was able to do is to use the multiple views system from UI-Router, but I need multiple instance of the same view to keep in memory (if multiple tickets are opened, they all are on the same view, with the same controller, but a different scope)
Here's my current implementation:
supportApp.js:
var app = angular.module("supportApp", ["ui.router", "ui.bootstrap"]);
app.config(function($stateProvider, $urlRouterProvider, $httpProvider){
$urlRouterProvider.otherwise("/");
$stateProvider
.decorator('d', function(state, parent){
state.templateUrl = generateTemplateUrl(state.self.templateUrl);
return state;
})
.state("main", {
abtract: true,
templateUrl: "main.html",
controller: "mainController"
})
.state("main.inbox", {
url: "/",
templateUrl: "inbox.html",
controller: "inboxController"
})
.state('main.viewTicket', {
url: '/ticket/{id:int}',
templateUrl: "viewTicket.html",
controller: "ticketController"
})
;
});
mainController.js: (handles other stuff, minimal code here)
app.controller("mainController", function($rootScope, $http, $scope, $state, $interval){
// Tabs system
$scope.tabs = [
{ heading: "Tickets", route:"main.inbox", active:false, params:{} }
];
var addTabDefault = {
heading: '',
route: null,
active: false,
params: null,
closeable: false
};
$rootScope.addTab = function(options){
if(!options.hasOwnProperty('route') || !options.route)
{
throw "Route is required";
}
var tabAlreadyAdded = false;
for(var i in $scope.tabs)
{
var tab = $scope.tabs[i];
if(tab.route == options.route && angular.equals(tab.params, options.params))
{
tabAlreadyAdded = true;
break;
}
}
if(!tabAlreadyAdded)
{
$scope.tabs.push($.extend({}, addTabDefault, options));
}
if(options.hasOwnProperty('active') && options.active === true)
{
$state.go(options.route, options.hasOwnProperty('params')?options.params:null);
}
};
$scope.removeTab = function($event, tab){
$event.preventDefault();
if($scope.active(tab.route, tab.params))
{
$scope.go($scope.tabs[0].route, $scope.tabs[0].params);
}
$scope.tabs.splice($scope.tabs.indexOf(tab), 1);
};
$scope.go = function(route, params){
$state.go(route, params);
};
$scope.active = function(route, params){
return $state.is(route, params);
};
$scope.$on("$stateChangeSuccess", function() {
$scope.tabs.forEach(function(tab) {
tab.active = $scope.active(tab.route, tab.params);
});
});
});
main.html:
<div class="container-fluid" id="sav-container">
<div class="row-fluid">
<div class="col-lg-2">
<form role="form" id="searchForm" action="#">
<div class="form-group has-feedback">
<input class="form-control" type="search" />
<span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
</form>
</div>
<div class="col-lg-10" id="support_main_menu">
<ul class="nav nav-tabs">
<li ng-repeat="t in tabs" ng-click="go(t.route, t.params)" ng-class="{active: t.active, closeable: t.closeable}" style="max-width: calc((100% - 128px) / {{tabs.length}});">
<a href class="nav-tab-text">
<button ng-show="t.closeable" ng-click="removeTab($event, t)" class="close" type="button">×</button>
<span>{{t.heading}}</span>
</a>
</li>
</ul>
</div>
</div>
<div class="row-fluid">
<div class="tab-content" ui-view></div>
</div>
</div>
It seems to me that what I ask is pretty standard, but I sadly couldn't find any usefull thing on the Internet
The basic idea is to store state (i.e. list of tickets) in a service as opposed to a controller. Services hang around for the life of the application. There are some articles on this. I'm still developing my approach but here is an example:
var RefereeRepository = function(resource)
{
this.resource = resource; // angular-resource
this.items = []; // cache of items i.e. tickets
this.findAll = function(reload)
{
if (!reload) return this.items;
return this.items = this.resource.findAll(); // Kicks off actual json request
};
this.findx = function(id)
{
return this.resource.find({ id: id }); // actual json query
};
this.find = function(id) // Uses local cache
{
var itemx = {};
// Needs refining
this.items.every(function(item) {
if (item.id !== id) return true;
itemx = item;
return false;
});
return itemx;
};
this.update = function(item)
{
return this.resource.update(item);
};
};
refereeComponent.factory('refereeRepository', ['$resource',
function($resource)
{
var resource =
$resource('/app_dev.php/referees/:id', { id: '#id' }, {
update: {method: 'PUT'},
findAll: {
method: 'GET' ,
isArray:true,
transformResponse: function(data)
{
var items = angular.fromJson(data);
var referees = [];
items.forEach(function(item) {
var referee = new Referee(item); // Convert json to my object
referees.push(referee);
});
return referees;
}
},
find: {
method: 'GET',
transformResponse: function(data)
{
var item = angular.fromJson(data);
return new Referee(item);
}
}
});
var refereeRepository = new RefereeRepository(resource);
// Load items when service is created
refereeRepository.findAll(true);
return refereeRepository;
}]);
So basically we made a refereeRepository service that queries the web server for a list of referees and then caches the result. The controller would then use the cache.
refereeComponent.controller('RefereeListController',
['$scope', 'refereeRepository',
function($scope, refereeRepository)
{
$scope.referees = refereeRepository.findAll();
}
]);

How to manually add a datasource to Angularjs-select2 when select2 is set up as <input/> to load remote data?

I am using the Select2 as a typeahead control. The code below works very well when the user types in the search term.
However, when loading data into the page, I need to be able to manually set the value of the search box.
Ideally something like: $scope.selectedProducerId = {id:1, text:"Existing producer}
However, since no data has been retrieved the Select2 data source is empty.
So what I really need to be able to do is to add a new array of data to the datasource and then set the $scope.selectedProducerId, something like: $scope.producersLookupsSelectOptions.addNewData({id:1, text:"Existing producer}) and then
$scope.selectedProducerId = 1;
Researching this I have seen various suggestions to use initSelection(), but I can't see how to get this to work.
I have also tried to set createSearchChoice(term), but the term is not appearing in the input box.
I would be most grateful for any assistance.
Thanks
This is the html
<div class="col-sm-4">
<input type="text" ui-select2="producersLookupsSelectOptions" ng- model="selectedProducerId" class="form-control" placeholder="[Produtor]" ng-change="selectedProducerIdChanged()"/>
</div>
This is the controller
angular.module("home").controller("TestLookupsCtrl", [
"$scope", "$routeParams", "AddressBookService",
function($scope, $routeParams, AddressBookService) {
$scope.producersLookupsSelectOptions = AddressBookService.producersLookupsSelectOptions();
}
]);
This is the service:
angular.module("addressBook").service("AddressBookService", [
"$http", "$q", function($http, $q) {
var routePrefix = "/api/apiAddressBook/";
//var fetchProducers = function(queryParams) {
// return $http.get(routePrefix + "GetClientsLookup/" + queryParams.data.query).then(queryParams.success);
//};
var _getSelectLookupOptions = function(url, minimumInputLength, idField, textField) {
var _dataSource = [];
var _queryParams;
return {
allowClear: true,
minimumInputLength: minimumInputLength || 3,
ajax: {
data: function(term, page) {
return {
query: term
};
},
quietMillis: 500,
transport: function(queryParams) {
_queryParams = queryParams;
return $http.get(url + queryParams.data.query).success(queryParams.success);
},
results: function(data, page) {
var firstItem = data[0];
if (firstItem) {
if (!firstItem[idField]) {
throw "[id] " + idField + " does not exist in datasource";
}
if (!firstItem[textField]) {
throw "[text] " + textField + " field does not exist in datasource";
}
}
var arr = [];
_.each(data, function(returnedData) {
arr.push({
id: returnedData[idField],
text: returnedData[textField],
data: returnedData
});
});
_dataSource = arr;
return { results: arr };
}
},
dataSource: function() {
return _dataSource;
},
getText: function (id) {
if (_dataSource.length === 0) {
throw ("AddressBookService.getText(): Since the control was not automatically loaded the dataSource has no content");
}
return _.find(_dataSource, { id: id }).text;
}
//initSelection: function(element, callback) {
// callback($(element).data('$ngModelController').$modelValue);
//},
//createSearchChoice:function(term) {
// return term;
//},
addNewData:function(data) {
this.ajax.results(data,1);
};
};
return {
producersLookupsSelectOptions: function() {
var url = routePrefix + "GetClientsLookup/";
return _getSelectLookupOptions(url, 2, "Id", "Name");
},
}
}
]);

Resources