Complete New to Ionic and Angular, need advice with external json request - javascript

I just started with ionic and I know this is probably super easy. I've been reading about how to use ionic and angular, but haven't been able to figure this easy little task out.
I just want to simply pull json from an external file. I'm still reading the docs, but can't manage to figure out how to do this just yet.
http://codepen.io/anon/pen/wKwxpX
var myApp = angular.module('myApp', ['ionic']);
myApp.controller('MainCtrl', function() {
//instead of hard coded json, I need to get json from an external source here
this.items = [
{title: "Item 1"},
{title: "Item 2"},
{title: "Item 3"},
{title: "Item 4"},
{title: "Item 5"},
]
for (var i = 0; i < 1000; i++)
this.items.push(i);
});

You could use $http call to make an ajax for external ajax and inside success call bind that result to the $scope variable.
Also you need to wrap title in " double quotes to make it valid json like "title"
Markup
<body ng-controller="MainCtrl as main">
<ion-header-bar class="bar-positive">
<h1 class="title">1000 Items</h1>
</ion-header-bar>
<ion-content>
<ion-list>
<ion-item collection-repeat="item in main.items">
{{item.title}}
</ion-item>
</ion-list>
</ion-content>
</body>
Controller
var myApp = angular.module('myApp', ['ionic']);
myApp.controller('MainCtrl', function($http) {
var main = this
$http.get('data.json').success(function(data){
main.items = data;
})
});
data.JSON
[{
"title": "Item 1"
}, {
"title": "Item 2"
}, {
"title": "Item 3"
}, {
"title": "Item 4"
}, {
"title": "Item 5"
}]
Demo Plunkr

Related

Recursive Components in AngularJS 1.x

Finally trying to learn AngularJS and I can't quite figure out how to make components work recursively. I have a simple example that's not rendering as expected.
HTML
<body ng-app="myApp" ng-controller="myCtrl as vm">
<nested-list list="vm.list"></nested-list>
</body>
JavaScript
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.list = [
{ "name": "Item 1" },
{ "name": "Item 2",
"subItems": [
{ "name": " Item 2.1" }
]
},
{ "name": "Item 3",
"subItems": [
{ "name": " Item 3.1" },
{ "name": "Item 3.2",
"subItems": [
{ "name": "Item 3.2.1" },
{ "name": "Item 3.2.2" }
]
}
]
}];
}])
.component('nestedList', {
bindings: {
list: '<'
},
template: `
<div ng-repeat="item in $ctrl.list" >
<div> {{item.name}} </div>
<nested-list list="item.subItems"></nested-list>
</div>
`
});
Undoubtedly because I'm missing something obvious, the list from the app's main controller myCtrl isn't getting bound to the root component. If anyone can provide insight, I'd be grateful.
Stephen
As you are using controllerAs, you should be binding values to controller this(context) instead of binding values to $scope.
.controller('myCtrl', [function() {
var vm = this;
vm.list = [ ..];
}]);
Plunker Here

Import JSON data for AngularJS Web App

I have been following the Angular tutorials, and I am trying to get my JSON data to appear, yet I know I am doing something wrong, but can't figure out the proper method.
I know that somewhere in my app.js my scope is messed up.
How can I display the Family Name of each product?
Here is the layout I have:
app.js
var eloApp = angular.module('eloMicrosite', []);
eloApp.controller('homeListController', ['$scope', '$http',
function($scope, $http) {
$http.get('/Elo/eloMS.min.json')
.success(function(data) {
$scope.products = data;
});
}]);
eloApp.controller('HomeController', function(){
this.products = $scope.products;
});
HTML
<div ng-controller="HomeController as home">
{{home.products[o]["Family Name"]}}
</div>
JSON Layout
{
"products": [
{
"Family Name": "3201L",
"Type": "IDS",
"Size (inches)": 32,
"Aspect Ratio": "16:9",
"Part Number": "E415988",
"Product Description": "ET3201L-8UWA-0-MT-GY-G",
"Marketing Description": "3201L 32-inch wide LCD Monitor",
"Advance Unit Replacement": "",
"Elo Elite": "",
"Package Quantity": 1,
"Minimum Order Quantity": 1,
"List Price": 1800
},
.
.
.
],
"families": [
{
category: "Category1"
},
{
category: "Category2"
}
],
"accessories": [
{
category: "Category1"
},
{
category: "Category2"
}
]
}
You should add homeListController on your page instead of HomeController, Also need to use this instead of using $scope as you wanted to follow controllerAs syntax, 2nd controller is useless in this scenario, you could remove that from app.js.
Markup
<div ng-controller="homeListController as home">
{{home.products[0]["Family Name"]}}
</div>
Controller
eloApp.controller('homeListController', ['$http',
function($http) {
var home = this;
$http.get('/Elo/eloMS.min.json')
.success(function(data) {
home.products = data.products; //products should mapped here
});
}]);
Demo Plunkr

I'm trying to print an array using a loop in Javascript in Angular JS

I'm trying to print out each array item from a property in an object:
{
position:"Finance Office Assistant",
employer:"Washtenaw County Finance Department",
location:"Ann Arbor, MI",
start_date:"2012",
current: false,
end_date:"2012",
duties: [
"Item 1",
"Item 2",
"Item 3"
]
},
This object is in an array, with several other objects. I'm trying to create a function that loops through all of the objects and prints out the duties array items in an unordered list with the exact number of list items and array items.
Here is the function I'm trying to write to do the task
$scope.dutyList = function() {
var arrayLength = $scope.duties.length;
while (arrayLength > 0) {
console.log("dutyList run")
document.write("<li> {{ dutyList }} </li>");
--arrayLength;
}
}
You don't need a function to handle displaying data like this. Angular's ngRepeat is for this. To access the second level of of your data set you can nest two repeats in your unordered list. The first one (in a div) repeats the first layer of your data, and exposes the second layer, which repeat in the <li> tag:
<ul>
<div ng-repeat="d in data">
<li ng-repeat="duty in d.duties">{{duty}}</li>
</div>
</ul>
Plunker
As a general rule, you don't want to write directly to the document when using a framework like Angular. Instead, you should use the built in templating system and directives to render your page.
I'm making some assumptions about the end goal here, but, assuming the array of objects can be accessed by the controller and attached to the scope, you could print your unordered list of duties for each position using something like the following.
angular.module('myApp', []).controller('myCtrl', function($scope){
$scope.foo = [{
position:"Finance Office Assistant",
employer:"Washtenaw County Finance Department",
location:"Ann Arbor, MI",
start_date:"2012",
current: false,
end_date:"2012",
duties: [
"Item 1",
"Item 2",
"Item 3"
]
}, {
position:"Another Position",
employer:"Another Employer",
location:"Ann Arbor, MI",
start_date:"2012",
current: false,
end_date:"2012",
duties: [
"2nd Object, Item 1",
"2nd Object, Item 2",
"2nd Object, Item 3"
]
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller='myCtrl'>
<div ng-repeat='bar in foo'>
<h1>{{ bar.position }}</h1>
<ul>
<li ng-repeat='duty in bar.duties'>
{{ duty }}
</li>
</ul>
</div>
</div>

Angularjs ng-repeat: iterate over a special object fields

I have an object:
var options = {
NAME_1 : "Name 1",
TEXT_1 : "Description goes here",
NAME_2 : "Name 2",
TEXT_2 : "Description2 goes here",
};
Is it possible to iterate over the fields of the object inside the ng-repeat?
E.g.
<div ng-repeat="item in options">
<span class="title">{{item.name}}</span>
<span class="text">{{item.text}}</span>
</div>
I will greatly appreciate any advice.
Thanks in advance.
Absolutely! Use the following syntax:
<div ng-repeat="(k, v) in options">
As you can guess, k is the key and v is the value of the key.
this is not going to work as you imagine, perhaps your object can look like this,
var options = [
{
name : "Name 1",
text : "Description goes here"
},
{
name : "Name 2",
text : "Description2 goes here"
}
];
now you can iterate just as you want it.
Or, you can I guess iterate over all your values in the object but you need to keep in mind that these values are not really related to each other, besides just being in the same object.
This is the solution with ng-if and iterate over the object. But as I mentioned, javascript iterates over objects not in order so your best bet to reorder your properties in an array and then iterate again. This below iterate as NAME_1, NAME_2, TEXT_1, TEXT_2
app.controller('MainCtrl', function($scope) {
var options = {
NAME_1 : "Name 1",
TEXT_1 : "Description goes here",
NAME_2 : "Name 2",
TEXT_2 : "Description2 goes here",
};
$scope.options = options;
$scope.check = function(title, key) {
if(key.split('_')[0] === title) {
return true;
}
}
});
<div ng-repeat="(k,v) in options|orderBy:k">
<span ng-class="title" ng-if="check('NAME',k)">{{k}}</span>
<span ng-class="text" ng-if="check('TEXT',k)">{{k}}</span>
</div>
COMPLETE SOLUTION:
If you also use underscore, you can do this.
<div ng-repeat="x in optionsArray">
<span ng-class="title" ng-if="check('NAME',x)">{{x[1]}}</span>
<span ng-class="text" ng-if="check('TEXT',x)">{{x[1]}}</span>
</div>
app.controller('MainCtrl', function($scope) {
var options = {
NAME_1: "Name 1",
TEXT_1: "Description goes here",
NAME_2: "Name 2",
TEXT_2: "Description2 goes here",
};
$scope.options = options;
$scope.optionsArray = _.pairs(options);
$scope.check = function(title, key) {
if (key[0].split('_')[0] === title) {
return true;
}
}
});

KendoUI ObservableArray children being clobbered by KendoUI treeView

Backstory
I'm using AngularJS/KendoUI and using angular-kendo-ui as a the 'bridge' between the two. I'm using Kendo for it's treeview component and this piece is a client requirement.
What I need to accomplish is
1. draw the tree menu from data provided by a service
2. periodically check each element in this data, and update a 'disabled' prop
3. redraw elements in the treeview based on the results from the above step.
Assumptions
1. If I want to be able to update the kendo tree view, then I need to use Kendo's observeables
2. I may be using Kendo's ObservableArray incorrectly here.
The problem
If I create a new ObservableArray like so
var things = new kendo.data.ObservableArray([{
text: "Parent 1",
items: [{text: "Child 1"}, {text: "Child 2"}, {text: "Child 3"}]
}])
things be logged to the console and the structure is intact.
However, once the treeview is instantiated with this data, further logging of things to the console show that the children (items) are no longer present. It is very hard to iterate over and update children if they don't exist!
Plunker here http://plnkr.co/edit/qJpIvK?p=info, if you view the 'script.js' file and open the console, you should be able to see my issue.
here is the code
HTML
<div ng-app="MyApp">
<div ng-controller="TreeController">
<div kendo-tree-view k-options="thingsOptions"></div>
</div>
</div>
JS
var app = angular.module("MyApp", ["kendo.directives"]);
app.controller('TreeController', function($scope, $timeout) {
var things = new kendo.data.ObservableArray([{
text: "Parent 1",
items: [{
text: "Child 1"
}, {
text: "Child 2"
}, {
text: "Child 3"
}]
}, {
text: "Parent 2",
items: [{
text: "Child 1"
}, {
text: "Child 2"
}, {
text: "Child 3"
}]
}]);
// should have 3 items
console.log('preTreeView init', things[1].items);
$scope.thingsOptions = {
dataSource: things
};
$timeout(function() {
// the 3 items expected are gone, why?
console.log('postTreeView init', things[1].items);
}, 1000);
});
Is this a misuse of ObservableArray and if so, what is the correct approach?
Internally, the TreeView widget turns your ObservableArray into a kendo.data.HierarchicalDataSource http://docs.telerik.com/kendo-ui/api/framework/hierarchicaldatasource which moves each of the children into DataSource objects of their own.
You can navigate them afterward like this:
var treeViewWidget = $(".k-treeview").data("kendoTreeView");
var dataSource = treeViewWidget.dataSource; // this is a HierachicalDataSource
var parents = dataSource.data(); // Parent1 and Parent2
var parent1 = parents[0];
var doesParent1HaveChildren = parent1.hasChildren; // true
var childrenDataSource = parent1.children; // this is a HierarchicalDataSource
var child1 = childrenDataSource.data()[0]; // this is {text: "Child 1"}

Categories

Resources