This is on of tough task that am facing in my school. am totally new to angularJs. i need to fetch one image out of all retrieved images from the database. And then when i refresh the page the next image want to appear.
for an example first "banner.jpg" appear when i refresh the page "banner1.jpg" want to appear. can anyone help me to do solve this problem. please.
This is my retrieved Json
{
"id": 1,
"path": "Content/Banner/banner.jpg"
},
{
"id": 2,
"path": "Content/Banner/banner1.jpg"
},
{
"id": 3,
"path": "Content/Banner/banner2.jpg"
},
{
"id": 4,
"path": "Content/Banner/banner3.jpg"
},
my angular controller.
appGM.controller('bannerCtrl', ['$scope', '$http', 'urls', function ($scope, $http, urls) {
var request = $http({
method: 'GET',
url: urls.api + 'Banner/Banners'
}).success(function (data, status) {
console.log(data);
console.log(JSON.stringify(data));
console.log(JSON.parse(JSON.stringify(data)));
$scope.BBanner = angular.fromJson(data);
})
.error(function (error) {
$scope.status = 'Unable to load dog images: ' + error.message;
console.log($scope.status);
});
And its my Html
<div class="row">
<div class="col-sm-3 sidenav" ng-repeat="d in BBanner">
<img ng-src="{{d.path}}">
</div>
you can use localstorage to store the in in the first time. After you refresh the page increment the value and save it to the same local storage and so on.
run this Demo multiple time to see the id change.
controller
if(!localStorage.getItem("uID")){
var s = {"id":1};
localStorage.setItem("uID", JSON.stringify(s))
}
$scope.data = [{
"id": 1,
"path": "Content/Banner/banner.jpg"
},
{
"id": 2,
"path": "Content/Banner/banner1.jpg"
},
{
"id": 3,
"path": "Content/Banner/banner2.jpg"
},
{
"id": 4,
"path": "Content/Banner/banner3.jpg"
}]
var item = localStorage.getItem("uID")
item = JSON.parse(item);
alert("Id = " + item.id)
item.id = item.id +1 ;
localStorage.setItem("uID", JSON.stringify(item))
$scope.clear = function(){
localStorage.removeItem("uID");
}
updated
add this to check the image. check the demo again
var item = localStorage.getItem("uID")
item = JSON.parse(item);
var obj = $scope.data.find(function(o){
return o.id === item.id
})
// add this lines
$scope.image =(obj)? obj.path : "invalid id";
if(item.id == 4){
localStorage.removeItem("uIDs");
item.id = 0;
}
item.id = item.id +1 ;
Related
the first json is coming from the API in get this data by making a http call
[
{
"clientid": 1,
"clientname": "facebook",
"forecasted": 18,
},
{
"clientid": 2,
"clientname": "youtube",
"forecasted": 83,
}
]
i create the second json to update the image on the first json
[
{
"clientid": 1,
"clientname": "facebook ",
"img":"images/21747.jpg"
},
{
"clientid": 2,
"clientname": "youtube",
"img": "images/youtube.svg"
},
]
now i need to macth both json base on the same id, and fill the first json that i coming from the api with images of the second json
app.factory('myFactory', function($http){
return{
client: function(callback){
$http({
method: "GET",
url: "http://www.erek.co.za/api/..",
cache:true
}).then(callback);
},
list: function(callback){
$http({
method: "GET",
url: "data/Client.json",
cache:true
}).then(callback);
}
};
});
app.controller('myController', function ($scope, myFactory) {
myFactory.client(function(response){
var data = response.data;
$scope.myClients = data;
})
myFactory.list(function (response) {
var data = response.data;
$scope.dark = data;
})
});
html
<div ng-repeat="client in myClients>
<a href="#{{client.clientid}}"
<div class="client-project-panel">
<div class="client-logo-container">
<div class="client-logo" >
<img ng-src="{{dark[$index].img}}" alt="{{client.clientname}}">
</div>
<div class="project-forecasted">
<h2 class="forecasted-value">{{client.forecasted}}%</h2>
<p>Complete</p>
</div>
</div>
</div>
</a>
You can use Object.assign method.
let array1=[ { "clientid": 1, "clientname": "facebook", "forecasted": 18, }, { "clientid": 2, "clientname": "youtube", "forecasted": 83, } ]
let array2 = [ { "clientid": 1, "clientname": "facebook ", "img":"images/21747.jpg" }, { "clientid": 2, "clientname": "youtube", "img": "images/youtube.svg" } ]
var expected = array1.map(a => Object.assign(a, array2.find(b => b.clientid == a.clientid)));
console.log(expected);
myFactory.client(function(response){
var data = response.data;
var clientsData = data;
// after you fetch the clients get list of images
myFactory.list(function (response) {
var data = response.data;
var clientImages = {}
for(var i=0;i<data.length;i++){
clientImages[data[i].clientid] = data[i].img
}
$scope.dark = clientImages
$scope.myClients = clientsData
})
})
In your template just refer to {{dark[client.clientid]}}
You might want to wrap your html in ng-if="myClients" so that the content is shown only after the data is fetched
I have two ajax calls. One to load release cycles in first dropdown and another to load scenarios in second dropdown. The scenarios in the second dropdown correspond to the value selected in first dropdown. I am unable to load both on page load. I have to go and select the value by clicking an option in the first dropdown, only then the options in the second dropdown get loaded. How can I achieve this functionality on page load and not by manually selecting or triggering that event.. I do not wish to use ko handlers. Thank you for help in advance.
//load release cycles in first dropdown
self.pushReleaseCycles = function(releaseCycleUrl,scenarioNameUrl1,scenarioNameUrl2){
$.ajax({
url: sharepointScenarioListUrl + releaseCycleUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items = data.d.results;
items.forEach( function(item) {
if (self.release_cycles.indexOf(item.Release_x0020_Cycle) == -1) {
self.release_cycles.push(item.Release_x0020_Cycle);
}
});
self.selectedCycle.subscribe(function(value) {
self.scenarios([]);
self.pushScenariosToDropdown(value,scenarioNameUrl1,scenarioNameUrl2);
});
},
error: function (data) {
alert("ERROR in function pushReleaseCycles : " + data);console.log(data);
}
});
};
//load scenarios in second dropdown
self.pushScenariosToDropdown = function(value,scenarioNameUrl1,scenarioNameUrl2){
$.ajax( {
url: sharepointScenarioListUrl + scenarioNameUrl1 + value + scenarioNameUrl2,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items = data.d.results;
items.forEach( function(item) {
self.scenarios.push(new ScenarioModel(item));
console.log(data);
});
self.selectedScenario.subscribe(function(value) {
dbName = ko.toJSON(value.title);
jarFile1 = ko.toJSON(value.jar);
fdMimoAvailable = ko.toJSON(value.fdmimo);
self.setValues(dbName,jarFile1,fdMimoAvailable);
});
},
error: function (data) {
alert("ERROR in function pushScenariosToDropdown: " + data);console.log(data);
}
});
};
My HTML:
<select id="dropdown" required class="form-control select2" data-bind="options: release_cycles,value:selectedCycle">
</select>
<select id="dropdown2" required="required" class="form-control select2" data-bind="options: scenarios, optionsText:'scenarioName',optionsCaption:'Please Select Scenario', value:selectedScenario,validationOptions: { errorElementClass:'input-validation-error' },selectedOptions: chosenScenario">
</select>
The way I would handle this is to change how the data is pulled from the server. You will want to include the entire menu structure as needed for the page. In my opinion it's better to have a slightly longer load than a choppy experience. Here's an example of nesting the menus and how that might look.
function ViewModel() {
var self = this;
self.Dropdown1 = ko.observableArray();
self.SelectedItem1 = ko.observable();
self.Dropdown2 = ko.computed(function() {
if (self.SelectedItem1() == null) {
return [];
};
console.log(ko.toJS(self.SelectedItem1()))
return self.SelectedItem1().Submenu;
});
self.SelectedItem2 = ko.observable();
self.LoadDropDown = function() {
self.Dropdown1.push({
"Name": "Hat",
"Value": "top",
"Submenu": [{
"Name": "Blue",
"Value": "#0000FF"
},
{
"Name": "Green",
"Value": "#00FF00"
},
{
"Name": "Red",
"Value": "#FF0000"
}
]
});
self.Dropdown1.push({
"Name": "Shirt",
"Value": "middle",
"Submenu": [{
"Name": "Striped",
"Value": "Striped"
},
{
"Name": "Logo",
"Value": "Logo"
},
{
"Name": "Plain",
"Value": "None"
}
]
});
self.Dropdown1.push({
"Name": "Pants",
"Value": "bottom",
"Submenu": [{
"Name": "Jeans",
"Value": "Jeans"
},
{
"Name": "Kakhis",
"Value": "Kakhis"
},
{
"Name": "Cordroy",
"Value": "Cordroy"
}
]
});
}
self.LoadDropDown();
}
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: Dropdown1, optionsText: 'Name', value: SelectedItem1"></select>
<select data-bind="options: Dropdown2, optionsText: 'Name', value: SelectedItem2"></select>
If you don't want to go retrieve the values from the server for the second select box based on the values of the first, but want to load the whole data set, then just load a json object of all of the options for the second box and then parse through that after the first selection. If it's a lot of data though, it's going to impact performance.
I'm new to Meteor and trying to figure out this issue I have.
I'm trying to load data from the Lessons collection based on the route being passed. e.g if /courses/level1/lesson1/1a is passed then show data
Unfortunately this doesn't work.
Am I on the right path or is there a better way of doing this?
Collection
{
"_id": "YSgr3fvjpEBn7ncRa",
"courseId": "level1",
"lesson": [
{
"lessonId": "lesson1",
"freeLesson": true,
"title": "Lesson 1",
"eachLesson": [
{
"eachLessonId": "1a",
"title": "This is (masculine)",
"video": "839843"
},
{
"eachLessonId": "1b",
"title": "That is (masculine)",
"video": "839843"
},
{
"eachLessonId": "1c",
"title": "This is (feminine)",
"video": "839843"
},
{
"eachLessonId": "1d",
"title": "That is (feminine)",
"video": "839843"
},
{
"eachLessonId": "1e",
"title": "Getting to know you",
"video": "839843"
}
]
}
]
}
Routes
Router.route("courses/:courseId/:lessonId/:eachLessonId", {
path:"/courses/:courseId/:lessonId/:eachLessonId",
layoutTemplate: "layoutLessons",
template:"lessons",
onBeforeAction:function(){
var currentUser = Meteor.userId();
if (currentUser) {
Session.set('courseId', this.params.courseId);
Session.set('lessonId', this.params.lessonId);
Session.set('eachLessonId', this.params.eachLessonId);
this.next();
} else {
Router.go('/')
}
},
});
Template helper
Template.lessons.onCreated(function(){
Meteor.subscribe('listLessons');
});
Template.lessons.helpers({
currentLesson: function() {
var currentLesson = Session.get('eachLessonId');
return Lessons.find({"lesson.eachLesson.eachLessonId" : currentLesson});
},
});
HTML
{{#each currentLesson}}
{{title}}
{{video}}
{{/each}}
Instead of storing courseId, lessonId and eachLessonId as Session values, you could use the Iron Router's waitOn and data option.
For example, you could rewrite your route as follows:
Router.route('/courses/:courseId/:lessonId/:eachLessonId', {
name: 'lessons',
layoutTemplate: 'layoutLessons',
template: 'lessons',
onBeforeAction: function() {
let currentUser = Meteor.user();
if (currentUser) this.next();
else Router.go('/');
},
data: function() {
var doc = Lessons.findOne({
"courseId": this.params.courseId,
"lesson.lessonId": this.params.lessonId,
"lesson.eachLesson.eachLessonId": this.params.eachLessonId
});
if (doc) {
var lesson = {};
var lessonId = this.params.eachLessonId;
_.each(doc.lesson, function(i) {
lesson = _.find(i.eachLesson, function(j) {
return j.eachLessonId == lessonId;
});
});
return lesson;
}
return {};
},
waitOn: function() {
return [
Meteor.subscribe('lesson', this.params.courseId, this.params.lessonId, this.params.eachLessonId)
];
}
});
This should set the data context to the requested eachLesson object. However, you may consider setting the data context to a document in the Lessons collection and then just picking certain eachLesson objects. In addition, you should create a publish function which returns just the requested Lessons document and not all of them, like you probably do now in your listLessons publication. You can pass all IDs as arguments to the corresponding publish function.
I am a newbie to angular js.This might be a piece of cake for many of you.
Could you please guide me?
I have a json file, a view to display, index.html(view), and a controller(index_angular.js).In the image the second and third columns are drop down menus corresponding to the technology id in json.
How to parse the json and display in the view according to the image as its attached.
Thanks in advance.
JSON STRUCTURE:
{
"technology": [
{
"id": "AKC",
"detail": {
"drop1": [
{
"id": "AKC-lst-1231"
},
{
"id": "AKC-lst-1232"
},
{
"id": "AKC-lst-1233"
}
],
"drop2": [
{
"id": "T_AKC_live"
},
{
"id": "T_AKC_Capt"
},
{
"id": "T_AKC_live1"
}
]
}
},
{
"id": "MET",
"detail": {
"drop1": [
{
"id": "MET-2st"
},
{
"id": "MET-34"
}
],
"drop2": [
{
"id": "sd-232"
},
{
"id": "sd-121"
}
]
}
}
]
}
Required Format to display in view in Angular JS:
Coloumn 2 and coloumn 3 are drop down menus of drop1 and drop2 of corresponding technology id
index_angular.js(CONTROLLER)
var myModule=angular.module('test',[]);
myModule.controller("test_controller", function($scope,$http){
$scope.message = "hello world!";
$scope.posts = "";
$scope.init=function(){
$scope.friends = ["Test friends","test1","test2","test4","test5","test6","test7","test8","test9","test10","test11","test12","test13","test113","test14","test114","test15","test133","test23","test33","test35"];
$http.get("test.json").
success(function(data, status, headers, config) {
$scope.posts = data;
alert($scope.posts);
$scope.tech_name=[];
$scope.technology="";
console.log($scope.posts);
var tech_marker_count= $scope.posts.technology.length;
alert(tech_marker_count);//count of technology
for(var tech_marker=0;tech_marker<tech_marker_count;tech_marker++)
{
$scope.tech_name.push($scope.posts.technology[tech_marker].id);
$scope.technology=$scope.posts.technology[tech_marker].id;
alert( $scope.technology);
}
}).
error(function(data, status, headers, config) {
alert("Error fetching data");
// log error
});
};
});
index.html(VIEW)
<div class="view_data">
<ul>
</ul>
</div>
You can take use of ng-repeat that does help you to loop through the json
Your html will look like below,
HTML
<div class="view_data" ng-init="init()">
<div ng-repeat="d in posts.technology|orderBy: 'id'">
{{d.id}}
|<span ng-repeat="drop1Item in d.detail.drop1">{{drop1Item.id}}</span>
|<span ng-repeat="drop2Item in d.detail.drop2">{{drop2Item.id}}</span>
</div>
</div>
Working Plunkr need some styling on it.
Now its turn to do design. Thanks.
I am new in sharepoint. I am using Sharepoint 2013.
I want to retrieve name and email id in People Or Group column using REST API.
My list contains two such columns. Please help me to retrieve title and email ids of both the columns
How to retrieve user field value using SharePoint REST
Using $expand OData operator you can specify that the request returns projected fields from User Information List list for user field.
ListItem resource endpoint: https://[site]/_api/web/lists/getbytitle('<list title>')/items(<item id>)?$select=<user field name>/Name,<user field name>/EMail&$expand=<user field name>
Examples
Assume a Tasks List that contains AssignedTo (multi-valued) and Author (single-valued) user fields.
The first example demonstrates how to retrieve AssignedTo column user details:
/_api/web/lists/getbytitle('Tasks')/items(1)?$select=AssignedTo/Name,AssignedTo/EMail&$expand=AssignedTo
returns Name and Title for AssigntedTo column:
{
"d": {
"__metadata": {
"id": "764f494a-7186-4b83-9db0-2bcf1a0930a5",
"uri": "https://contoso.sharepoint.com/_api/Web/Lists(guid'71284427-d86e-424f-ae07-2e0c53b9ac4a')/Items(1)",
"etag": "\"3\"",
"type": "SP.Data.TasksListItem"
},
"AssignedTo": {
"results": [
{
"__metadata": {
"id": "a06b28ff-9356-4aa9-8f38-f75107058fd2",
"type": "SP.Data.UserInfoItem"
},
"Name": "i:0#.f|membership|username#contoso.onmicrosoft.com",
"EMail": "username#contoso.onmicrosoft.com"
}
]
}
}
}
The following example demonstrates how to retrieve Author and AssignedTo user field user values:
Endpoint Url: /_api/web/lists/getbytitle('Tasks')/items(1)?$select=Author/Name,Author/EMail,AssignedTo/Name,AssignedTo/EMail&$expand=AssignedTo,Author
Result:
{
"d": {
"__metadata": {
"id": "e29690e4-3813-44ce-a828-160ad072666d",
"uri": "https://contoso.sharepoint.com/_api/Web/Lists(guid'71284427-d86e-424f-ae07-2e0c53b9ac4a')/Items(1)",
"etag": "\"3\"",
"type": "SP.Data.TasksListItem"
},
"Author": {
"__metadata": {
"id": "6dc8fe57-1865-464f-aaa3-f7b8bb555f20",
"type": "SP.Data.UserInfoItem"
},
"Name": "i:0#.f|membership|username#contoso.onmicrosoft.com",
"EMail": "username#contoso.onmicrosoft.com"
},
"AssignedTo": {
"results": [
{
"__metadata": {
"id": "b9a1d6f8-4bec-4ec8-b940-fdaeac2eff37",
"type": "SP.Data.UserInfoItem"
},
"Name": "i:0#.f|membership|username#contoso.onmicrosoft.com",
"EMail": "username#contoso.onmicrosoft.com"
}
]
}
}
}
JavaScript example
function getItemDetails(webUrl,listTitle,itemId,selectFields, expandFields){
var endpointUrl = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + itemId + ")";
endpointUrl+= '?$select=' + selectFields.join(",");
endpointUrl+= '&$expand=' + expandFields.join(",");
return executeRequest(endpointUrl,'GET');
}
function executeRequest(url,method,headers,payload)
{
if (typeof headers == 'undefined'){
headers = {};
}
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if(method == "POST") {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var selectFields = ['Author/Name','Author/EMail','AssignedTo/Name','AssignedTo/EMail'];
var expandFields = ['Author','AssignedTo'];
getItemDetails(webUrl,'Tasks',2,selectFields,expandFields)
.done(function(data){
//print MULTI-valued user field: AssignedTo
console.log('AssignedTo user field value:')
for(var i = 0; i< data.d.AssignedTo.results.length;i++) {
console.log(data.d.AssignedTo.results[i].EMail);
console.log(data.d.AssignedTo.results[i].Name);
}
//print SINGLE-valued user field: Author
console.log('Author user field value:')
console.log(data.d.Author.EMail);
console.log(data.d.Author.Name);
});