SOS, $scope not working on algular js - javascript

i am making a http.get that is giving me this answer below, that i am getting from a localhost json:
[
{
"_id": 52562,
"title": "Event name",
"startDate":"20-03-20",
"endDate": "20-03-20",
"description": "Lorem ipsun doloren he jlhdkh skjrlkuslinf sidhkjh this is a test",
"imageUrl": [
"https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg",
],
"donateTypes": [{
"_id": 1,
"name": "Fraldas",
"min": 2,
"total": 12
}, {
"_id": 1,
"name": "Fraldas",
"min": 2,
"total": 12
}, {
"_id": 1,
"name": "Fraldas",
"min": 2,
"total": 12
}]
}
];
The thing is, in my html the scope is not rendering, i really don't know why and i have already tried everything! i dont know what to do! anybody can help?
index.html:
<!DOCTYPE html>
<html ng-app="saoVicentinoApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<script data-require="angular-route#*" data-semver="1.2.14" src="https://code.angularjs.org/1.2.14/angular-route.js"></script>
<script src="app.js"></script>
<script src="EventController.js"></script>
<script src="github.js"></script>
</head>
<body>
<h1>Sao Vicente</h1>
<div ng-view></div>
</body>
</html>
github.js
(function(){
var github = function($http){
var getUser = function(){
return $http.get("http://localhost/course1/finalAndCorrect/json")
.then(function(response){
return response.data;
});
};
return{ //what i return will represent the public api
getUser: getUser
};
};
var module = angular.module("saoVicentinoApp");
module.factory("github", github);
}());
app.js:
(function(){
var app = angular.module("saoVicentinoApp", ["ngRoute"]);
app.config(function($routeProvider){ //do this configuration when bringing this module to life
$routeProvider
.when("/", {
templateUrl:"user.html",
controller:"EventController"
})
.otherwise({redirectTo:"/"});
});
}());
EventController.js:
(function(){
angular.module('saoVicentinoApp')
.controller('EventController', ['$scope', 'github', function($scope, github){
$scope.test = 4;
var onUserComplete = function(data){
$scope.event = data;
console.log($scope.event);
};
var onError = function(reason){
$scope.error = "Could not fetch the data.";
};
github.getUser()
.then(onUserComplete, onError);
}]);
}());
user.html
<!-- event Container -->
<div class="list-group">
<!-- event Container -->
<div class="list-group-item">
<h3>{{event.title}}
<em class="pull-right">{{event.startDate}} - {{event.endDate}}</em>
</h3>
<!-- Image Gallery -->
<div ng-show="event.imageUrl.length">
<!-- Fail 1 Message -->
<div ng-show="event.imageUrl">
<img class="img img-circle img-thumbnail center-block" ng-src="{{event.imageUrl[0]}}" />
<!-- <ul class="clearfix">
<li class="small-image pull-left thumbnail" ng-repeat="image in event.imageUrl"> <img ng-src="{{image}}" /> </li>
</ul>-->
</div>
</div>
<section>
<ul class="nav nav-pills">
<li><a href ng-click="tab = 1">Description</a></li>
<li><a href ng-click="tab = 2">Como posso contribuir?</a></li>
<li><a href ng-click="tab = 3">Calendario</a></li>
</ul>
<div class="panel" ng-show="tab === 1">
<h4>Description</h4>
<blockquote>{{event.description}}</blockquote>
</div>
<div class="panel" ng-show="tab === 2">
<h4>Como posso contribuir?</h4>
<div ng-repeat="donations in event.donateTypes">
<div>{{donations.name}}</div>
<div>{{donations.min}}</div>
<div>{{donations.total}}</div>
</div>
</div>
<div class="panel" ng-show="tab === 3">
<h4>Calendario</h4>
<blockquote>None yet</blockquote>
</div>
</section>
</div>
</div>

remove the promise from the factory. Since you are using promise(.then) from then controller no need to use it from the factory. Just return the http request
github.js
(function(){
var github = function($http){
var getUser = function(){
return $http.get("http://localhost/course1/finalAndCorrect/json")
};
return{ //what i return will represent the public api
getUser: getUser
};
};
var module = angular.module("saoVicentinoApp");
module.factory("github", github);
}());
You json is also invalid
[
{
"_id":52562,
"title":"Event name",
"startDate":"20-03-20",
"endDate":"20-03-20",
"description":"Lorem ipsun doloren he jlhdkh skjrlkuslinf sidhkjh this is a test",
"imageUrl":[
"https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg"
],
"donateTypes":[
{
"_id":1,
"name":"Fraldas",
"min":2,
"total":12
},
{
"_id":1,
"name":"Fraldas",
"min":2,
"total":12
},
{
"_id":1,
"name":"Fraldas",
"min":2,
"total":12
}
]
}
]
And data in http response comes under data property. So change this
var onUserComplete = function(data){
$scope.event = data.data[0];
console.log($scope.event);
};

Related

Can't access a nested JSON object in HTML

AngularJS V1.6.4
$scope.aCourse["name"] is logged to console correctly, but in the HTML code nothing is populated into the screen.
$scope.getCourse = function(idd){
$http.defaults.headers.common['Authorization'] = 'Basic ' + btoa($cookieStore.get('username') + ':' + $cookieStore.get('password') );
$http({
method: 'GET',
url: 'http://localhost:8080/course/'+idd,
}).then(function successCallback(response) {
$scope.aCourse = response.data;
console.log($scope.aCourse["name"]);
window.location = "/website-take-course.html";
}, function errorCallback(response) {
alert("Course data in fetching failed");
});
}
HTML Code:
<div class="page-section padding-top-none" ng-repeat="c in aCourse" >
<div class="media media-grid v-middle">
<div class="media-left">
<span class="icon-block half bg-blue-300 text-white">1</span>
</div>
<div class="media-body" >
<h1 class="text-display-1 margin-none" >{{c.name}}</h1>
</div>
</div>
<br/>
<p class="text-body-2">{{c.description}}</p>
</div>
Based on your post, it lookes like $scope.aCourse is a object, not an array.
change it as follows,
<div class="page-section padding-top-none" ">
<div class="media media-grid v-middle">
<div class="media-left">
<span class="icon-block half bg-blue-300 text-white">1</span>
</div>
<div class="media-body">
<h1 class="text-display-1 margin-none">{ aCourse.name }}</h1>
</div>
</div>
<br/>
<p class="text-body-2">{{aCourse.description}}</p>
</div>
or use something like this to iterate over object,
<div ng-repeat="(key,value) in aCourse">
{{key}} : {{value}}
</div>
DEMO
var app = angular.module('filterApp', []);
app.controller('myCtrl', function($scope) {
$scope.aCourse = {
"content": "SO",
"description": "Programmers"
};
});
<!DOCTYPE html>
<html >
<head>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script src="https://code.angularjs.org/1.4.7/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="filterApp" ng-controller="myCtrl">
<div ng-repeat="(key,value) in aCourse">
{{key}} : {{value}}
</div>
</body>
</html>
There could be a two situations :
1. $scope.aCourse is an array of objects [{},{},{}].
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.aCourse = [
{
"name": "alpha",
"description" : "description1"
},
{
"name": "beta",
"description" : "description2"
},
{
"name": "gamma",
"description" : "description3"
}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div class="page-section padding-top-none" ng-repeat="c in aCourse" >
<div class="media-body" >
<h1 class="text-display-1 margin-none" >{{c.name}}</h1>
</div>
<p class="text-body-2">{{c.description}}</p>
</div>
</div>
2. $scope.aCourse is an Object {......}.
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.aCourse = {
"name": "alpha",
"description" : "description1"
};
console.log($scope.aCourse["name"]);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div class="page-section padding-top-none" ng-repeat="(key, value) in aCourse" >
<div class="media-body" >
<h1 class="text-display-1 margin-none" >{{value}}</h1>
</div>
</div>
</div>
In your angular code you are setting aCourse to the response data. You then access the data as an object with:
$scope.aCourse["name"]
Then in your html you are running an ng-repeat on $scope.aCourse as if it were an array of objects:
<div class="page-section padding-top-none" ng-repeat="c in aCourse" >
You would either need to make aCourse an array of objects to use your current html, or update your html and access the object in aCourse with aCourse.name and aCourse.description.

How to create Bootstrap grid

I want to format output of a json file, that I read in Angular. I want to use a bootstrap grid, but I tried and I had no success.The files are:
test.html
<html>
<head>
<script src="bower_components/angular/angular.min.js"></script>
<script src="test.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body ng-app="MyApp" ng-controller="TestCtrl">
<ul>
<div class="row">
<div class="col-md-2">
<li ng-repeat-start="pat in patients">
<strong> {{pat.name}}</strong>
</li>
</div>
<div class="col-md-2">
<li ng-repeat-end ng-repeat="diag in pat.diagnose">
{{diag.disease}}
</li>
</div>
</div>
</ul>
</body>
test.js
var App = angular.module('MyApp', []);
App.controller('TestCtrl', function($scope, $http) {
$http.get('test.json').success(function(data){
$scope.patients = [];
angular.forEach(data.patients, function(value, key){
$scope.patients.push(value);
});
});
});
test.json
{
"patients": [
{
"name": "Abcd",
"diagnose":[
{"disease":"Ddd"},
{"disease":"Rrrr"},
{"disease":"Aaaaa"}
]
},
{
"name": "Efghij",
"diagnose":[
{"disease":"Hhhhh"}
]
},
{
"name": "Klmnop",
"diagnose":[
{"disease":"Gggggg"}
]
},
{
"name": "Qrst",
"diagnose":[
{"disease":"Oooooo"},
{"disease":"Xxxxxx"}
]
}
]
}
I want to have on each row: Name (col 1), Disease (col2). (diseases listed vertically). Coul you help me plese
You can try this,
var App = angular.module('MyApp', []);
App.controller('TestCtrl', function($scope) {
$scope.patients = [
{
"name": "Abcd",
"diagnose":[
{"disease":"Ddd"},
{"disease":"Rrrr"},
{"disease":"Aaaaa"}
]
},
{
"name": "Efghij",
"diagnose":[
{"disease":"Hhhhh"}
]
},
{
"name": "Klmnop",
"diagnose":[
{"disease":"Gggggg"}
]
},
{
"name": "Qrst",
"diagnose":[
{"disease":"Oooooo"},
{"disease":"Xxxxxx"}
]
}
];
});
angular.bootstrap(document, ['MyApp']);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-controller="TestCtrl" class="container">
<div class="row" ng-repeat="pat in patients">
<div class="col-md-2">
<strong> {{pat.name}}</strong>
</div>
<div class="col-md-2">
<ul>
<li ng-repeat="diag in pat.diagnose">
{{diag.disease}}
</li>
</ul>
</div>
</div>
</body>
Try this:
https://jsfiddle.net/RLQhh/6393/
<ul ng-repeat="pat in patientsList.patients">
<div class="row">
<div class="col-md-6">
<li>
<strong> {{pat.name}}</strong>
</li>
</div>
<div class="col-md-6">
<li ng-repeat="diag in pat.diagnose">
{{diag.disease}}
</li>
</div>
</div>
</ul>
I was very unclear. The grid structure I want to create the grid is :
Patient_1 Disease_1_Patient_1
Disease_1_Patient_1
Disease_2_Patient_1
------------------------------------------------
Patient_2 Disease_1_Patient_2
Disease_2_Patient_2
------------------------------------------------
and so on.
I hope it will be useful for someone else. Finaly, I got the result I wanted.I changed the HTML file as follows (I'll show only the body section):
<body ng-app="MyApp" ng-controller="TestCtrl">
<div class="container" ng-repeat="pat in patients">
<div class="row">
<div class="col-md-2">{{pat.name}}</div>
<div class="col-md-2"><ul><li ng-repeat="diag in pat.diagnose">{{diag.disease}}</li></ul></div>
</div>
</div>
</body>
I reach this result, by creating first a HTML table like this:
<table ng-repeat="artist in artists">
<tr>
<td>{{artist.name}}</td>
<td ><ul><li ng-repeat="album in artist.albums">{{album.title}}</li></ul></td>
</tr>
</table>
Then I replaced:
<table>
with
<div class="container">,
<tr>
with
<div class="row">
and
<td>
with
<div class="col-xx-xx">

How i can filter my data in angularJS throw links?

i have
in html its looks like:
<ul class="filter-ul">
<li class="filter-li">
<span class="filter-title">Все бренды</span>
<ul class="filter-ul" ng-repeat="brand in vendors |filter:query_brand">
<li class="filter-li">{{ brand.name }}</li>
</ul>
</li>
</ul>
One item in my Json looks like this:
{
"name": "Bra by Joseline",
"category": null,
"price": 8370.0,
"old_price": 8370.0,
"vendor": {
"id": 1,
"name": "Agent Provocateur",
"seo_name": ""
},
"recommended": [],
"id": 750
}
i want filtering my items by "vendor.name" field and i have no idea how make it reality, its my first expirience in angularJS, sorry for noob question :)
My controller look like this:
(function () {
'use strict';
angular
.module('beo.products.controllers')
.controller('ProductsListController', ProductsListController);
ProductsListController.$inject = ['$scope', '$http'];
function ProductsListController($scope, $http) {
$scope.setMainClasses('catalog-page');
activate();
function activate() {
$http.get('api/v1/products/').success(function(data) {
$scope.products = data;
$scope.ProductSortLeft = '-id'; //по умолчанию фильтроваться будут по обновлению
});
$http.get('api/v1/categories/').success(function(data) {
$scope.categories = data;
});
$http.get('api/v1/shops/').success(function(data) {
$scope.shops = data;
});
$http.get('api/v1/vendors/').success(function(data) {
$scope.vendors = data;
});
}
}
})();
I use filter columns like these:
<filter></filter>
<!-- CATALOG -->
<div class="catalog-main" id="catalog">
<div class="catalog-result-options hidden-xs">
<div class="result-alert" id="result-show-modal">Уведомление о рапродаже</div>
<select class="selectpicker" ng-model="ProductSortLeft">
<option value="-price">Самые дорогие</option>
<option value="price">Самые дешевые</option>
<option value="click_count">Популярные</option>
<option value="-id">Новые</option>
</select>
</div>
<div class="catalog-item" ng-repeat="product in products | orderBy:ProductSortLeft">
<div class="item-pre-title">
Бесплатная доставка $150+
</div>
<div class="item-img">
<a href="/products/{{ product.id }}/"><img ng-src="{{ product.picture[0].external_img_url }}" width="150px"
height="150px" alt=""></a>
</div>
{{ product.name }}
<div class="item-price">
<div class="price-old">{{ product.old_price }}</div>
<b>{{ product.price }}</b>
</div>
<div class="item-footer">
<div class="item-sales-alert">
Получить скиду
</div>
</div>
</div >
You can filter on vendor.name like this:
var app = angular.module('myapp', []);
app.controller('myctrl', function($scope) {
$scope.filter = "";
$scope.brands = [{
"name": "Bra by Joseline",
"category": null,
"price": 8370.0,
"old_price": 8370.0,
"vendor": {
"id": 1,
"name": "Agent Provocateur",
"seo_name": ""
},
"recommended": [],
"id": 750
}, {
"name": "Another brand",
"category": null,
"price": 8370.0,
"old_price": 8370.0,
"vendor": {
"id": 1,
"name": "Agent Bond",
"seo_name": ""
},
"recommended": [],
"id": 750
}]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="myctrl">
<input ng-model="filter" placeholder="filter" />
<ul class="filter-ul" ng-repeat="brand in brands | filter: {vendor: {name: filter}}">
<li class="filter-li">{{ brand.name }}</li>
</ul>
</div>

ng-show Displaying all items

Continue working with angularjs and now having problem with ng-show which on click it show me all hidden data. As I understand, I need to specify ID of clicked item which I want to show, from my example i'm using ng-model which had boolean value and on click it change on true, that's why it's showing all items. Tell me please, how can I show item which I had selected?
<div class="list-group" ng-click="SetItemVisible()" ng-repeat="q in feed">
<a href="" class="list-group-item">
<h4 ng-model="showItem" class="list-group-item-heading">{{q.title}}</h4>
<p ng-show="showItem" value="true" class="list-group-item-text">{{q.body}}</p>
</a>
</div>
And js:
$scope.SetItemVisible = function () {
if (!$scope.showItem) {
$scope.showItem = true;
} else {
$scope.showItem = false;
}
}
$scope.feed = [];
function getRssItems() {
rssFeedService.getFeed().then(function (results) {
$scope.feed = results.data;
}, function (error) {
//alert(error.data.message);
});
}
You can do dis by:
$scope.feed = [{
'title': "A",
'body': "testA body"
},
{
'title': "b",
'body': "testb body"
}
]
$scope.showItem = {};
$scope.SetItemVisible = function (index) {
$scope.showItem[ index] = true;
}
<div class="list-group" ng-click="SetItemVisible($index)" ng-repeat="q in feed track by $index">
<a href="" class="list-group-item">
<h4 ng-model="showItem[$index]" class="list-group-item-heading">{{q.title}}</h4>
<p ng-show="showItem[$index]" value="true" class="list-group-item-text">{{q.body}}</p>
</a>
For live demo click here: http://plnkr.co/edit/ApI9eb8eQlBdoMUkn8do?p=preview
<div class="list-group" ng-click="q.showItem != q.showItem" ng-repeat="q in feed">
<a href="" class="list-group-item">
<h4 ng-model="showItem" class="list-group-item-heading">{{q.title}}</h4>
<p ng-show="q.showItem" value="true" class="list-group-item-text">{{q.body}}</p>
</a>
</div>
Assuming following JSON for feed
[
{
"title":"test1",
"body":"test body 1",
"show":false
},
{
"title":"test2",
"body":"test body 2",
"show":false
}
]
HTML
<body ng-controller="MainCtrl">
<div class="list-group" ng-repeat="q in feed">
<a class="list-group-item">
<h4 ng-click="q.show=!q.show" class="list-group-item-heading">{{q.title}}</h4>
<p ng-show="q.show" value="true" class="list-group-item-text">{{q.body}}</p>
</a>
</div>
JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.feed = [];
$http.get('feed.json').then(function (results) {
$scope.feed = results.data;
}, function (error) {
//alert(error.data.message);
});
});
Check out here

emberjs arraycontroller issue

I am new to Ember and am having an issue. I would like the user to be able to select a number of workstations, and when they hit the next button, I would like the controller to create a number of objects equal to the number the user selected. Once they are taken to the next screen I want to view to append a number of divs with the questions equal to the number the user selected.
I have this for the app.js:
//Initialize the application
App = Ember.Application.create({
rootElement: '#main'
});
//Initialize the data model
App.CustomerController = Ember.Object.extend({
first: null,
last: null,
email: null,
phone: null,
clinic: null,
number: null
});
App.Workstation = Ember.Object.extend({
id: null,
title: null,
newOrExisting: null,
cabling: null
});
App.workstationController = Ember.ArrayController.create({
content: [],
num: null,
init: function() {
this.set('content',[]);
var num = this.get('num');
var tempId = Date.now();
var ws = App.Workstation.create({
id: tempId
});
this.pushObject(ws);
}
});
App.selectNoComputers = ["1", "2", "3", "4", "5"];
App.workstationSelect = ["Counter 1", "Counter 2", "Counter 3", "Counter 4", "Office 1", "Office 2", "Office 3"];
App.yesNo = ["New", "Existing"];
App.Router.map(function(match) {
match("/").to("captcha");
match("/customer").to("customer");
match("/wsnum").to("computers");
match("/overview").to("overview");
});
App.CaptchaRoute = Ember.Route.extend({
renderTemplate: function() {
this.render('captcha');
}
});
App.CustomerRoute = Ember.Route.extend();
App.ComputersRoute = Ember.Route.extend();
App.OverviewRoute = Ember.Route.extend({
});
App.initialize();
And this for my html:
<script type="text/x-handlebars" data-template-name="overview">
<div class="navbar">
<div class="navbar-inner">
<div class="progress-bar-label-div">
Progress:
</div>
<div class="progress-bar-div">
<div class="progress progress-striped">
<div class="bar" style="width:60%;"></div>
</div>
</div>
<div class="btn-group pull-right">
{{#linkTo "computers" class="btn"}}
Prev
{{/linkTo}}
</div>
</div>
</div>
<div class="row-a top">
<div class="pull-left" >
<h3>Workstation Overview</h3>
</div>
<div class="pull-right">
</div>
</div>
{{#each App.workstationController}}
<div class="workstation-b">
<div class="row-b">
<div class="pull-left workstation-title" >
<h4>{{id}}</h4>
</div>
<div class="pull-right form-inputs input-text">
<a class="btn btn-primary" >
Start
</a>
</div>
</div>
<div class="row-b">
<div class="pull-left questions">
What station will this be?
</div>
<div class="pull-right form-inputs input-text">
{{view Ember.Select prompt="Please Select" contentBinding="App.workstationSelect"}}
</div>
</div>
<div class="row-b">
<div class="pull-left questions">
Is this computer a new purchase or replacing and existing workstation?
</div>
<div class="pull-right form-inputs input-text">
{{view Ember.Select prompt="Please Select" contentBinding="App.yesNo"}}
</div>
</div>
</div>
{{/each}}
</script>
I'm sure I'm missing something pretty easy, but any help is appreciated.
I put together a fiddle to illustrate my problem.
Working fiddle: http://jsfiddle.net/mgrassotti/xtNXw/3/
Relevant changes: Added an observer to listen for changes to the num property. When it changes, the content array is reset and then an appropriate number of blank workstation objects are created.
App.workstationController = Ember.ArrayController.create({
content: [],
num: null,
init: function() {
this.set('content',[]);
},
addBlankWorkstation: function() {
var tempId = Date.now();
var ws = App.Workstation.create({
id: tempId
});
this.pushObject(ws);
}
});
App.workstationController.addObserver( 'num', function() {
var num = this.get('num');
this.set('content',[]);
for (var i=0;i<num;i++) {
this.addBlankWorkstation();
}
});
I hesitated to say working fiddle above since there are many things that might be worth refactoring. You'll find most of the complexity could be reduced by following ember naming conventions. Suggest looking at latest guides for more detail.

Categories

Resources