AngularJS Array Not Loading On View Load, but Alerts/Console Work - javascript

I am trying to push values into an array as follows, but it is showing as an empty array. Alerting works. I am sure I am missing something obvious. Any clues? I have included the code with the just the array push attempt and another entry of code that has working alerts.
$scope.termsArray = [];
execOperation();
function execOperation() {
//Current Context
var context = SP.ClientContext.get_current();
//Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
//Term Stores
var termStores = taxSession.get_termStores();
//Name of the Term Store from which to get the Terms.
var termStore = termStores.getByName("Taxonomy_111111111111");
//GUID of Term Set from which to get the Terms.
var termSet = termStore.getTermSet("12345-55-689");
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(function () {
var termEnumerator = terms.getEnumerator();
while (termEnumerator.moveNext()) {
var currentTerm = termEnumerator.get_current();
$scope.termsArray.push({
termName: currentTerm.get_name(),
termGUID: currentTerm.get_id(),
termSynonyms: 'Coming Soon'
});
}
}, function (sender, args) {
console.log(args.get_message());
});
}
Here is the code with working alerts:
function execOperation() {
//Current Context
var context = SP.ClientContext.get_current();
//Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
//Term Stores
var termStores = taxSession.get_termStores();
//Name of the Term Store from which to get the Terms.
var termStore = termStores.getByName("Taxonomy_111111111111");
//GUID of Term Set from which to get the Terms.
var termSet = termStore.getTermSet("12345-55-689");
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(function () {
var termEnumerator = terms.getEnumerator();
var termList = "Terms: \n";
while (termEnumerator.moveNext()) {
var currentTerm = termEnumerator.get_current();
$scope.termsArray.push({
termName: currentTerm.get_name(),
termGUID: currentTerm.get_id(),
termSynonyms: 'Coming Soon'
});
termList += currentTerm.get_id() + currentTerm.get_name() + "\n";
}
alert(termList);
}, function (sender, args) {
console.log(args.get_message());
});
}
Here is the HTML output:
<div> {{termsArray}}</div>
It returns []
Update: If I click in an input box and back out, or click an alert and hit ok, it then loads the array instead of loading on page load.

I was able to track the issue down. It appears that Angular doesn't respect non-Angular functions on load, so I needed to wrap the $scoped array in a $scope.apply. Please see here for details: Execute SharePoint Function On Page Load in AngularJS Application ($scope issue???)

Related

ServiceNow UI Page GlideAjax

I created a form using UI Page and am trying to have some fields autopopulated onChange. I have a client script that works for the most part, but the issue arises when certain fields need to be dot-walked in order to be autopopulated. I've read that dot-walking will not work in client scripts for scoped applications and that a GlideAjax code will need to be used instead. I'm not familiar with GlideAjax and Script Includes, can someone help me with transitioning my code?
My current client script looks like this:
function beneficiary_1(){
var usr = g_user.userID;
var related = $('family_member_1').value;
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee',usr);
rec.addQuery('sys_id',related);
rec.query(dataReturned);
}
function dataReturned(rec){
//autopopulate the beneficiary fields pending on the user selection
if(rec.next()) {
$('fm1_ssn').value = rec.ssn;
$('fm1_address').value = rec.beneficiary_contact.address;
$('fm1_email').value = rec.beneficiary_contact.email;
$('fm1_phone').value = rec.beneficiary_contact.mobile_phone;
var dob = rec.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0] ;
$('fm1_date_of_birth').value = date;
}
}
fm1_address, fm1_email, and fm1_phone do not auto populate because the value is dot walking from the HR_Beneficiary table to the HR_Emergency_Contact table.
How can I transform the above code to GlideAjax format?
I haven't tested this code so you may need to debug it, but hopefully gets you on the right track. However there are a couple of steps for this.
Create a script include that pull the data and send a response to an ajax call.
Call this script include from a client script using GlideAjax.
Handle the AJAX response and populate the form.
This is part of the client script in #2
A couple of good websites to look at for this
GlideAjax documentation for reference
Returning multiple values with GlideAjax
1. Script Include - Here you will create your method to pull the data and respond to an ajax call.
This script include object has the following details
Name: BeneficiaryContact
Parateters:
sysparm_my_userid - user ID of the employee
sysparm_my_relativeid - relative sys_id
Make certain to check "Client callable" in the script include options.
var BeneficiaryContact = Class.create();
BeneficiaryContact.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getContact : function() {
// parameters
var userID = this.getParameter('sysparm_my_userid');
var relativeID = this.getParameter('sysparm_my_relativeid');
// query
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee', userID);
rec.addQuery('sys_id', relativeID);
rec.query();
// build object
var obj = {};
obj.has_value = rec.hasNext(); // set if a record was found
// populate object
if(rec.next()) {
obj.ssn = rec.ssn;
obj.date_of_birth = rec.date_of_birth.toString();
obj.address = rec.beneficiary_contact.address.toString();
obj.email = rec.beneficiary_contact.email.toString();
obj.mobile_phone = rec.beneficiary_contact.mobile_phone.toString();
}
// encode to json
var json = new JSON();
var data = json.encode(obj);
return data;
},
type : "BeneficiaryContact"
});
2. Client Script - Here you will call BeneficiaryContact from #1 with a client script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var usr = g_user.userID;
var related = $('family_member_1').value;
var ga = new GlideAjax('BeneficiaryContact'); // call the object
ga.addParam('sysparm_name', 'getContact'); // call the function
ga.addParam('sysparm_my_userid', usr); // pass in userID
ga.addParam('sysparm_my_relativeid', related); // pass in relative sys_id
ga.getXML(populateBeneficiary);
}
3. Handle AJAX response - Deal with the response from #2
This is part of your client script
Here I put in the answer.has_value check as an example, but you may want to remove that until this works and you're done debugging.
function populateBeneficiary(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
answer = answer.evalJSON(); // convert json in to an object
// check if a value was found
if (answer.has_value) {
var dob = answer.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0];
$('fm1_ssn').value = answer.ssn;
$('fm1_address').value = answer.address;
$('fm1_email').value = answer.email;
$('fm1_phone').value = answer.mobile_phone;
$('fm1_date_of_birth').value = date;
}
else {
g_form.addErrorMessage('A beneficiary was not found.');
}
}

set taxonomy field multiple values

I'm creating a sharepoint hosted app which is based on javascript only. I wanted to update a multivalue taxonomy field in a list so I wrote this function which didn't work. there is a very little support for javascript csom online.
var list = context.get_web().get_lists().getByTitle('Company');
var item = list.getItemById(2);
var field = list.get_fields().getByInternalNameOrTitle("Departments");
var taxField = context.castTo(field, SP.Taxonomy.TaxonomyField);
var terms = new SP.Taxonomy.TaxonomyFieldValueCollection(context,
'Unit 1|5bf47d1f-d890-49d1-a844-85628ca508fd;#Unit 4|334ad23d-d2d8-4acb-ab09-38d2bacb97d4',
taxField);
taxField.setFieldValueByValueCollection(item, terms);
item.update();
context.load(taxField);
context.executeQueryAsync(
function() {
console.log('field updated');
});
I also used this code
var list = context.get_web().get_lists().getByTitle('Company');
var item = list.getItemById(2);
item.set_item('Departments', 'Unit 1|5bf47d1f-d890-49d1-a844-85628ca508fd;Unit 4|334ad23d-d2d8-4acb-ab09-38d2bacb97d4');
item.update();
context.executeQueryAsync(
function() {
console.log('field updated');
});
You must include a fake wssid (lookup id) prefix to the value. Below is a code I use to set a multiple value term field from jsom in the app model. This works.
function SetManagedMetaDataField() {
appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
context = new SP.ClientContext(appweburl);
factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
var list = appContextSite.get_web().get_lists().getByTitle('Documents');
var item = list.getItemById(5);
var field = list.get_fields().getByInternalNameOrTitle("Cars");
var taxField = context.castTo(field, SP.Taxonomy.TaxonomyField);
var terms = new SP.Taxonomy.TaxonomyFieldValueCollection(context,
'-1;#ATS|9f3e8e20-593b-471d-a145-81ff8664fd96;#-1;#CTS|8b18f6df-22be-4548-92b4-8f240d8fbfe5',
taxField);
taxField.setFieldValueByValueCollection(item, terms);
item.update();
context.load(taxField);
context.executeQueryAsync(
function () {
alert('field updated');
}, function (sender,args) {
alert(args.get_message() + '\n' + args.get_stackTrace());
});
}

Javascript to Read/Count Sharepoint 2010 List Items

I am having a lot of trouble with this. Essentially, I am trying to count the number of times Decommission appears in a particular list column. From what I can tell, the javascript is correct, but it doesn't work. Can anyone provide some guidance? Thanks!
<script type="text/javascript">
var myItems = null;
var siteUrl = &apos;https://chartiscorp.sp.ex3.secureserver.net/&apos;
function SuperDuper()
{
var queryString = &apos;<View><Query><Where><Gt><FieldRef name="End State" /><Value Type="String">Decommission</Value></Gt></Where></Query></View>&apos;;
var myContext = new SP.ClientContext(siteUrl);
var myWeb = myContext.get_web();
var myList = myWeb.get_lists().getByTitle(&apos;System_Information&apos;);
var myQuery = new SP.CamlQuery();
myQuery.set_viewXml(queryString);
myItems = myList.getItems(myQuery);
myContext.load(myItems,&apos;Includes(End State)&apos;);
myContext.executeQueryAsynch(Function.createDelegate(this,SuperDuperSuccess),Function.createDelegate(this,SuperDuperFail));
}
function SuperDuperFail(sender, args)
{
alert(&apos;Failed &apos; + args.get_message());
}
function SuperDuperSuccess(sender, args)
{
var endStateEnumerator = myItems.getEnumerator();
var decommCount = 0;
while(endStateEnumerator.moveNext())
{
//var currentEndState = endStateEnumerator.get_current();
decommCount = decommCount + 1;
}
alert(decommCount);
}
window.onload = SuperDuper;
</script>
What is the error?
Have you tried to see the script error it is throwing?
In function SuperDuperSuccess() you can simply put
var count=0;
count=this.myItems.get_count();
No need to write while loop .
Pls try to put alert and after some line and see what is coming.

Passing Variable from JSON data

I am building a mobile app using Titanium for ios and I am having a tough time getting my arms wrapped around passing variables. I am using a combination of local database and remote database to deliver my data. In this case I want to pass the data on the tableViewRow selected. The label that displays the data I call "categorydescription". In my table.addEventListener, I want to pass that data as the title for the new window and I will pass that same data to my php file on the remote server. Here is the code I am trying to use:
var xhr = Ti.Network.createHTTPClient({
onload: function() {
Ti.API.debug(this.responseText);
var json = JSON.parse(this.responseText);
for (i = 0; i < json.cms_client.length; i++) {
client = json.cms_client[i];
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true
});
var categorydescription = Ti.UI.createLabel({
text:client.catdesc,
font:{fontSize:'16dp', fontWeight:'bold'},
height:'auto',
left:'10dp',
color:'#000'
});
row.add(categorydescription);
tableData.push(row);
}
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: ??});
var catdesc = ??;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});
table.setData(tableData);
Would someone be so kind to tell me what I need to put in place of the ?? in the 'title' and 'var catdesc' above?
Just add the category description and title to the row object itself:
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true,
categoryDescription : client.catdesc, //Add this
clientTitle : client.title // Add this
});
Now get them in the listener:
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: e.row.title});
var catdesc = e.row.categoryDescription;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});

How to get the SharePoint list item from multiple site collections using JavaScript

Can anyone tell me how to get the SharePoint list item using JavaScript?
I have two site collections: site1 and site2. I am working in site1 application and I want to get the list items of site2. How can I achieve this? Please help me.
This is the code I am using on JavaScript side:
var ctx;
var listItem;
var title;
var col1;
var col2;
function SetItemValue(listItemId, listId, siteUrl, webUrl) {
ctx = new SP.ClientContext.get_current();
var web;
var site = ctx.get_site(siteUrl);//Here passing the second sitecollection url
if (webUrl != undefined && webUrl != '')
web = site.openWeb(webUrl);
else
web = site.openWeb('');
var list = web.get_lists().getById(listId);//Here passing the valid guid of list id
listItem = list.getItemById(listItemId);
ctx.load(list);
ctx.load(listItem);
ctx.executeQueryAsync(OnListLoaded);
list.update();
web.update();
ctx.load(web);
}
function OnListLoaded() {
listItem.set_item(col1, 'Hi');
listItem.set_item(col2, 'Test');
listItem.update();
ctx.load(listItem);
ctx.executeQueryAsync(OnListUpdated, OnError);
}
function OnListUpdated(args) {
}
function OnError(sender, args) {
alert(args.get_message());
}
It shows a message like "List does not exist". I think it will check the list from first site collection, which is why this message will popup. Can anyone help me to resolve this please?
Thanks,
Rasu
You can use the "constructor" new ClientContext(serverAbsoluteUrl) to create a context for a specific URL:
function SetItemValue(listItemId, listId, siteUrl, webUrl) {
ctx = new SP.ClientContext(siteUrl);
var web;
var site = ctx.get_site(siteUrl);//Here passing the second sitecollection url
if (webUrl != undefined && webUrl != '')
web = site.openWeb(webUrl);
// ...

Categories

Resources