I have a Drop down in my Anjularjs Application implemented using 'ui.select2'
I had initialized it as below
<input type="text" ng-model="objCas.iProjectId" id=" iprojectid" ui-select2="iProjectIdOption" />
And My Js Implementation is getting data from remote server with pagination and filter
var app = angular.module('CASApp', ['ui.select2', 'checklist-model']);
app.controller('CASController', function ($scope, $http) {
$scope.iProjectIdOption = {
placeholder: "Click to choose the Project...",
allowClear: true,
initSelection: function (element, callback) {
},
ajax: {
url: "/Prj/dummy/Ajaxlist",
quietMillis: 0,
type: "POST",
data: function (term, page) {
return {
q: term,
page: page,
listType: "ProjectDetails"
}; // query params go here
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
var more = (page * 30) < data.total_count; // whether or not there are more results available
return {
results: $.map(data.items, function (item) {
return {
text: item.text,
id: item.id
}
}),
more: more
}
},
cache: true
}
}
}
}
Everything works fine .I am able to use all the features and post the values also. But problem is with setting the already selected values at time of edit
Tried
$Scope.objCas.iProjectId= {"text":"2010 / 256 - / dummytext","id":240}
$Scope.objCas.iProjectId=2;
$scope.iProjectId.selected = {"text":"2010 / 256 - / dummytext","id":240}
Get the select2 element object and apply the following code:
angular.element("#select2_id").select2('data', { "text": "text", "id": [id]});
HTML code: no need of id
<input type="text" ng-model="objCas.iProjectId" ui-select2="iProjectIdOption" />
js code:
use only this for default biniding
$Scope.objCas.iProjectId= {"text":"2010 / 256 - / dummytext","id":240}
example code:
link: http://embed.plnkr.co/K66Pf0/
replace script.js file:
// Code goes here
var myAppModule = angular.module('MyApp', ['ui.select2']);
myAppModule.controller('MyController', function($scope) {
$scope.select2Options = {
initSelection: function (element, callback) {
},
ajax: {
url: "./data.json",
data: function (term, page) {
return {}; // query params go here
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data}
}
}
}
console.log("$scope.select2Options-",$scope.select2Options.initSelection);
$scope.testModel={ "id": 4, "text": "Fourth", "color": "red" }
;
});
you can view default selected value in dropdown.
Related
I have a html page which I am including as follows.
<ng-include src="lowerTabURL"></ng-include>
This page contains a devextreme control which loads a datasource via ajax.
html:
<div class="tab-container" style="height:100%; width:100%">
<div dx-tabs="lowerTabOptions" dx-item-alias="lowerTab">
</div>
</div>
controller:
DemoApp.controller('NavigationController', function DemoController($scope, $templateCache) {
$scope.lowerTabURL = "LowerPanelTest";
$scope.currentSidebarId = 10100;
$scope.lowerTabOptions = {
dataSource: new DevExpress.data.CustomStore({
load: function (loadTabOptions) {
console.log('get tabs');
var d = $.Deferred();
$.ajax({
url: 'GetLowerTabs',
data: { currentSidebarId: $scope.currentSidebarId },
type: 'GET',
success: function (result) { console.log(result); d.resolve(result); }
});
return d.promise();
}
}),
animationEnabled: true,
swipeEnabled: true,
itemTitleTemplate: 'title',
height: '100%'
};
$scope.navBarClicked = function (sidebarId) {
console.log(sidebarId);
$scope.currentSidebarId = sidebarId;
}
});
This works correctly however I have a navbar which when clicked, should change the tab control.
Currently I am changing the sidebarId which gets passed to the ajax call but I need a way to reload the include page so that this is called again. I have tried changing the lowerTabUrl and then changing it back again but this doesnt refresh the page. What is the best way to do this?
It depends on your angular version, you will need to watch after changes of value for param sidebarId, # angular 1 this is achieved by scope.watch
scope.$watch('sidebarId', function(newValue, oldValue) {
// ..call refresh here
});
at angular 1.5 and later you can override ngOnChages
this.$onChanges = function (changesObj) {
if (changesObj.sidebarId) {
// changesObj.sidebarId.currentValue
}
};
At the moment I am retrieving data from the server.
[
{
id:1,
name:demo,
request: {
id: 1,
localCompany: {
id: 1
}
}
}]
[{ }, { }] so this is how my json object looks.
When I get call the $http service and put it in the gridOptions: {data: this.data}
I get this error in the console window: TypeError: newRawData.forEach is not a function.
data: ng.IPromise<any[]> = this.programService.getRequestsForProgram(this.model.id).then((data: any) => {
console.log(data);
return data;
});
gridOptions: {} = {
data: this.data ,
paginationPageSize: 5
//columnDefs: this.programCountryService.getHeaders()
};
This is the code I am using at the moment.
Any idea how I can get rid of this error? And is it possible that the grid only shows localCompany.Id and not the name:demo?
Try to put the data in $scope.data
Like $scope.data=getdata from server
and then
gridOptions: {} = {
data: $scope.data ,
paginationPageSize: 5
//columnDefs: this.programCountryService.getHeaders()
};
Put data into $scope and than to gridOptions.data = $scope.data.
If you want to show only data for localCompany.id you need to make definition for columnDefs for field request with custom template like:
'<div class="ui-grid-cell-contents">{{ COL_FIELD.id }}</div>'
We are working on a Web application with angularJS and using spring/hibernate.
We are using Linux operating system in production environment and Development environment is Windows.We are trying implement online document editing tool like ms-word in our application.
After some research we are using OnlyOffice https://api.onlyoffice.com/ .
I am using the following angularJs component to use onlyOffice
https://github.com/legalthings/angular-onlyoffice
We are able to integrate it with the application and we can see the opened document in the editor in web browser.
But my changes are not being saved.The control is not reaching the callBackUrl.
Since angularJs component uses onSave method which is not there in OnlyOffice API anymore.So i have changed the code in html and JS file a bit:-
HTML file code is:-
<div ng-controller="DocumentEditController">
<onlyoffice-editor src="{{ trustSrc(document.src) }}"
title="{{ document.name }}">
</onlyoffice-editor>
</div>
And JS file code is:-
angular.module('onlyoffice', []);
angular.module('onlyoffice').directive('onlyofficeEditor', [function () {
function key(k) {
var result = k.replace(new RegExp("[^0-9-.a-zA-Z_=]", "g"), "_") + (new
Date()).getTime();
return result.substring(result.length - Math.min(result.length, 50));
}
var getDocumentType = function (ext) {
if (".docx.doc.odt.rtf.txt.html.htm.mht.pdf.djvu.fb2.epub.xps".indexOf(ext) != -1) return "text";
if (".xls.xlsx.ods.csv".indexOf(ext) != -1) return "spreadsheet";
if (".pps.ppsx.ppt.pptx.odp".indexOf(ext) != -1) return "presentation";
return null;
};
return {
template: '<div id="onlyoffice-editor"></div>',
link: function ($scope, $element, $attrs) {
$scope.$watch(function () {
return $attrs.src;
}, function () {
if (!$attrs.src) return;
var docUrl = $attrs.src;
var docTitle = $attrs.title || docUrl;
var docKey = key(docUrl);
var docType = docUrl.split('?')[0].substring(docUrl.lastIndexOf(".") + 1).trim().toLowerCase();
var documentType = getDocumentType(docType);
var config = {
type: "desktop",
width: '100%',
height: '100%',
documentType: documentType,
document: {
title: docTitle,
url: docUrl,
fileType: docType,
key: docKey,
permissions: {
edit: true,
download: false
}
},
editorConfig: {
mode: 'edit',
callbackUrl:"/documentSave"
},
events: {
onReady: function () {alert("in on ready");
setTimeout(function () {
$scope.$apply(function () {
$scope.ready = true;
});
}, 5000);
},
onError: function (event) {
alert(event.data);
// var url = event.data;
// $scope.save({url: url, close: $scope.close});
},
}
};
//creating object editing
new DocsAPI.DocEditor("onlyoffice-editor", config);
});
}
}
}]);
I changed the documenSave to the fully qualified name using localhost and appname also but that is also not working.
Any help is highly appreciated.
Edit
CallBackUrl is being called now on close of browser button...But our requirement is to save the document on click of save button.
Thanks in advance.
The fact is that clicking on the "Save" button creates a temp file in the document editor. The working document version will only be created after closing the document editor by all users (in ten seconds).
It is impossible to download the changed document in real time (before closing it).
My API populates some nested models. Using a shopping example, when you query orders, the items property is populated with the description and quantity instead of returning just the item IDs.
orders: [
{_id: 1,
items: [
{_id: 100,
description: "apple", // from lookup in the Items table
quantity: 4 // from lookup in the Items table
}, ...
],
...
}, ...
]
My view looks like:
<div ng-repeat="order in vm.orders">
<ul ng-repeat="item in order.items">
<li ng-model="vm.orders[$parent.$index].items[$index].description" ng-blur="item.$update()"></li>
<li ng-model="vm.orders[$parent.$index].items[$index].quantity" ng-blur="item.$update()"></li>
</ul>
</div>
The goal is to let the user update the item description and quantity from this view. (The lis are contenteditable directives.) The update call should be made on the Item $resource, not the Order $resource.
Is there a way to get Angular to recognize that the embedded documents are Items, upon which I can call methods like $update?
The workaround that I have is to change the ng-blur to call a controller method equivalent to this:
ng-blur="Item.update({_id: item._id})"
(If I do that, there's also no point in using the $parent.$index and $index syntax -- just order.item and item.description.)
What you want to do is transform the nested resources into actual resources. To do so, add a response transformer to your Order resource. For example
.factory('Order', function($resource, $http, Item) {
var responseTransformer = function(order) {
order.items = order.items.map(function(item) {
return new Item(item);
});
return order;
};
// somewhat lifted from https://docs.angularjs.org/api/ng/service/$http#overriding-the-default-transformations-per-request
var appendResponseTransformer = function(transformer) {
var defaults = $http.defaults.transformResponse;
defaults = angular.isArray(defaults) ? defaults : [defaults];
return defaults.concat(transform);
};
return $resource('/orders', whatever, {
get: {
method: 'GET',
url: '/orders/:id',
params: { id: '#id' },
transformResponse: appendResponseTransform(responseTransformer)
},
query: {
method: 'GET',
isArray: true,
transformResponse: appendResponseTransform(function(orders) {
return orders.map(responseTransformer);
})
}
});
});
An alternative to this would have been to just handle the item update in your controller. For example
ng-blur="updateItem(item)"
with
$scope.updateItem = function(item) {
Item.update(item);
};
I have very simple question about getting data from WebSql
I have DropDown i.e
<select id="selectCatagoryFood" data-role="listview" data-native-menu="true"
ng-init="foodCatagory = foodCatagories.cast[0]"
ng-options="foodCatagory as foodCatagory.text for foodCatagory in foodCatagories.cast"
ng-model="foodCatagory"
ng-change="changeFoodCatagory()">
</select>
now i want to add data init from webSQL. I already get Data from webSql but i am confuse that how to add that data into DropDown
An example or hints maybe very helpful for me.
Update 1 :: Add Controller Code
myApp.controller('foodSelection',function($scope,foodCatagories){
$scope.foodCatagories = foodCatagories;
$scope.changeFoodCatagory = function(){
alert($scope.foodCatagory.value);
}
});
Update 2 webSQL and JayData
_context.onReady({
success: showData,
error: function (error){
console.log(error);
}
});
function showData(){
var option = '';
_context.FoodGroup.forEach(function(FG)
{
option += '<option value="'+FG.FoodGroupID+'">'+FG.Description+'</option>';
}).then(function(){
console.log(option);
});
}
Update 3
var myApp = angular.module('myApp',[]);
myApp.factory('foodCatagories',function(){
var foodCatagories = {};
foodCatagories.cast = [
{
value: "000",
text: "Select Any"
}
];
return foodCatagories;
});
Update 4
One thing that i didn't mention is that I am using JayData for getting data from webSQL to my App
I will try to explain how it works:
EDIT: Live demo
html
Here is your stripped down select.
<select ng-options="item as item.text for item in foodCategories"
ng-model="foodCategory"
ng-required="true"
ng-change="changeFoodCategory()">
</select>
The directive ng-options will fill automatically the option elements in your select. It will take the foodCategories variable from the $scope of your controller and foreach item in the collection, it will use the text property as the label shown (<option>{{item.text}}</option>') and it will select the whole objectitemas the value of the selectedoption. You could also refer to a property as the value like ({{item.text}}). Then yourng-modelwould be set to theid` value of the selected option.
The directive ng-model corresponds to the variable in the $scope of your controller that will hold the value of the selected option.
The directive ng-required allows you to check if a value has been selected. If you are using a form, you can check if the field is valid formName.ngModelName.$valid. See the docs for more details on form validation.
The directive ng-change allows you to execute a function whenever the selected option changes. You may want to pass the ng-model variable to this function as a parameter or call the variable through the $scope inside the controller.
If no default value is set, angular will add an empty option which will be removed when an option is selected.
You did use the ng-init directive to select the first option, but know that you could set the ng-model variable in your controller to the default value you would like or none.
js
Here I tried to simulate your database service by returning a promise in the case that you are doing an async request. I used the $q service to create a promise and $timeout to fake a call to the database.
myApp.factory('DbFoodCategories', function($q, $timeout) {
var foodCategories = [
{ id: 1, text: "Veggies", value: 100 },
{ id: 2, text: "Fruits", value: 50 },
{ id: 3, text: "Pasta", value: 200 },
{ id: 4, text: "Cereals", value: 250 },
{ id: 5, text: "Milk", value: 150 }
];
return {
get: function() {
var deferred = $q.defer();
// Your call to the database in place of the $timeout
$timeout(function() {
var chance = Math.random() > 0.25;
if (chance) {
// if the call is successfull, return data to controller
deferred.resolve(foodCategories);
}
else {
// if the call failed, return an error message
deferred.reject("Error");
}
}, 500);
/* // your code
_context.onReady({
success: function() {
deferred.resolve(_contect.FoodGroup);
},
error: function (error){
deferred.reject("Error");
}
});
*/
// return a promise that we will send a result soon back to the controller, but not now
return deferred.promise;
},
insert: function(item) {
/* ... */
},
update: function(item) {
/* ... */
},
remove: function(item) {
/* ... */
}
};
});
In your controller you set the variables that will be used in your view. So you can call your DbFoodCategories service to load the data into $scope.foodCategories, and set a default value in $scope.foodCategory that will be used to set the selected option.
myApp.controller('FoodSelection',function($scope, DbFoodCategories){
DbFoodCategories.get().then(
// the callback if the request was successfull
function (response) {
$scope.foodCategories = response; //response is the data we sent from the service
},
// the callback if an error occured
function (response) {
// response is the error message we set in the service
// do something like display the message
}
);
// $scope.foodCategory = defaultValue;
$scope.changeFoodCategory = function() {
alert($scope.foodCatagory.value);
}
});
I hope that this helped you understand more in detail what is happening!
See this example and how use $apply to update the data in scope.
in the new version we released a new module to support AngularJS. We've started to document how to use it, you can find the first blogpost here
With this you should be able to create your dropdown easily, no need to create the options manually. Something like this should do the trick:
myApp.controller('foodSelection',function($scope, $data) {
$scope.foodCatagories = [];
...
_context.onReady()
.then(function() {
$scope.foodCatagories = _context.FoodGroup.toLiveArray();
});
});
provided that FoodGroup has the right fields, of course