ng-repeat does not work when I use it - angularjs

my code as follows:
<ons-template id="stockSearch.html">
<ons-page ng-controller="stockSymbolController">
<ons-toolbar class="DCF">
<div class="left">
<ons-back-button style="color:white;"></ons-back-button>
</div>
<div class="center" style="font-size:22px;" >Stock Search : {{myDCFNavigator.getCurrentPage().options.symbol}}</div>
</ons-toolbar>
<div class="stockSearchList">
<div ng-repeat="stockSearch in stocksSearchList">
<div class="stockSearchOne">
<div class="stockSearchOneComp">{{stockSearch.company}}</div>
<div class="stockSearchOneInfo">Symbol: {{stockSearch.symbol}}| Exchange:{{stockSearch.exchange}} </div>
</div>
</div>
</div>
</ons-page>
and script.js as follows:
module.controller('stockSymbolController', function($scope, $http){
$scope.stocksSearchList = new Object();
var url = "https://www.xxxxx.com/api/public/search_company/"+myDCFNavigator.getCurrentPage().options.symbol;
$.ajax({
type: 'get',
url: url,
success: function(data) {
$scope.stocksSearchList = data;
console.log($scope.stocksSearchList);
},
});
});
but the ng-repeat does not work.when I add the <div ng-repeat="stockSearch in stocksSearchList"> Even in the middle just display "123" , it would not show.
Anybody knows the reason?

Firstly you should use angular's $http service not jQuery's $.ajax method. From the docs:
The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.
So your code should look more like this:
module.controller('stockSymbolController', function($scope, $http){
var url = "https://www.xxxxx.com/api/public/search_company/"+myDCFNavigator.getCurrentPage().options.symbol;
$http.get(url)
.then(function(response) { // success is being deprecated in favour of .then
$scope.stocksSearchList = response.stocksSearchList; // this should be an array that has nested objects that include properties and values for company, symbol and exchange (see note below)
console.log($scope.stocksSearchList);
}, function(error) {
// do something with the error
});
});
I'm assuming response looks like the below with two items in the array:
{
stocksSearchList: [
{
company: 'some company',
symbol: 'some symbol',
exchange: 'some exchange'
},
{
company: 'some other company',
symbol: 'some other symbol',
exchange: 'some other exchange'
}
]
}

Instead of:
$scope.stocksSearchList = new Object();
Try
$scope.stocksSearchList = [];
And make sure this returns a list;

Related

AngularJs Component and angularjs-dropdown-multiselect

I am new to AngularJs world and was trying to use angularjs-dropdown-multiselect inside component.
Component's HTML looks like:
<div>
<select id="statusSelection" class="form-control"
ng-options="status.name for status in $ctrl.statuses track by status.id"
ng-model="$ctrl.status" ng-change="$ctrl.filterChanged()"></select>
</div>
<div ng-dropdown-multiselect="" options="$ctrl.categories" selected-model="$ctrl.category"
events="$ctrl.events">
</div>
Event on status changed and category will call the same action.
MultiselectController.prototype.filterChanged = function() {
this.onFilterChange({
status: this.status,
category: this.category});
};
MultiselectController.prototype.events = {
onItemSelect: function(item) {
filterChanged();
},
onItemDeselect: function(item) {
filterChanged();
}
};
When I try to run the above code and change the status, the code works as expected but fails during Category change(error in console).
Error message: ReferenceError: filterChanged is not defined
Angular version: 1.5.8
angularjs-dropdown-multiselect: 1.11.8
Plunker: http://plnkr.co/edit/JL7N6M?p=preview
Thanks for helping me out here.
I have created an instance variable and initialize it to instance of Controller.
var _instance;
function MultiselectController($scope) {
this.statuses = testMultiselect.statuses;
this.categories = testMultiselect.categories;
this.$scope = $scope;
this.setDefault();
_instance = this;
}
Now, I am using this instance variable to access the functions on Controller.
MultiselectController.prototype.events = {
onItemSelect: function(item) {
_instance.filterChanged();
},
onItemDeselect: function(item) {
_instance.filterChanged();
}
};
I am not completely happy with this as there should be better way to do the same but until I find, I will keep this.
Updated Plunker: http://plnkr.co/edit/D7BKI9?p=preview

NodeJS + AngularJS $http get

I am using Nodejs and AngularJS and i am having a problem with filling a table in the front-end from a generated JSON file.
I have the below ejs file:
<% include layout %>
<div class="panel panel-info">
<div class="panel-heading">
<h3 class= "panel-title"> <%=title %></h3>
</div>
<br>
<div
data-ng-app="projectionsModule"
data-ng-controller="projectionsController">
<div class="container">
<%include projectionsGrid%>
</div>
</div>
<script src="/bower_components/angular/angular.min.js"></script>
<script src="../../javascripts/app/projections/projectionsModule.js"> </script>
<script src="../../javascripts/app/projections/projectionsService.js"></script>
<script src="../../javascripts/app/projections/projectionsController.js"></script>
and the projectionsGrid.ejs as of below:
<table
data-ng-show="projections.length > 0"
class='table table-striped table-hover'
>
<tr class="success">
<td>Name</td>
<td>Age</td>
</tr>
<tr data-ng-repeat="projection in projections">
<td>{{projection.Name}}</td>
<td>{{projection.Age}}</td>
</tr>
</table>
The controller is the following:
angular.module("projectionsModule")
.controller("projectionsController", projectionsController);
projectionsController.$inject = ['$scope', 'projectionsService'];
function projectionsController($scope, projectionsService) {
// $scope.projections = [];
getAllProjections();
function getAllProjections() {
projectionsService.getAllProjections().
success(function (response) {
$scope.projections = response.projections;
alert(response.projections);
// console.log(response.projections[0]);
})
}
}
and the Service :
angular.module("projectionsModule")
.factory("projectionsService", projectionsService);
projectionsService.$inject = ['$http'];
function projectionsService($http) {
return {
getAllProjections : function () {
return $http.get('/getAllProjections');
}
};
}
It seems that the
projectionsService.getAllProjections().
success(function (response) {
$scope.projections = response.projections;
does not work.
In the browser with Inspect all files are loaded correctly.
The json file is the below:
{
"projections": [
{
"name": "Alex",
"age": "18"
}
]
}
The printscreen i get when i run it:
enter image description here
Could someone please help mew cause i really do not know what else to do.
Thank you.
Print screen with error:
enter image description here
Please see related plunker.
You are using promises wrong. If you need explanation, ask me in a comment.
// Mandatory code for plunkr link
In your case, instead of returning an object, just make a $http call and delete the timeout. I'll let you do it, but if you need help, feel free to ask.
EDIT AFTER COMMENT you forgot to include $http as a dependency. You can also use $http.get, which is faster and (for me at least) easier to understand (see the documentation here)
angular.module("projectionsModule")
.factory("projectionsService", function($q, $http) {
return {
projectionFunction: projectionFunction
}
function projectionFunction() {
return $http.get('127.0.0.1:1337/getAllProjections', {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
});
EDIT WITH SOLUTION You need to use $q to use promises. Take a look into it, you will use it very often with your http requests. Your function should look like this :
angular.module("projectionsModule")
.factory("projectionsService", function($q, $http) {
return {
projectionFunction: projectionFunction
}
function projectionFunction() {
var defer = $q.defer();
$http.get('127.0.0.1:1337/getAllProjections', {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(success) {
defer.resolve(success);
}, function(error) {
defer.reject(error);
});
return defer.promise;
}
});
In your controller, you can then do something like that :
function getAllProjections() {
projectionsService.projectionFunction().then(function(success) {
$scope.projections = success.data.projections;
// do an alert(success) to see what is in it !
}, function(error) {
alert(error.data);
});
}

After make ajax-post request the html elements are not refresh in angular

I have a issue.i make ajax-post request then it execute properly then i get the response.After process the response i need again make ajax-get then those data i set to a variables in the scope.the data are successfully assign in to variable but html elements are not refresh.this is the sample code.
this is html part
<div ng-controller="AppManagerCtrl" >
<md-list-item ng-repeat="app in apps">
<div>
<div flex="20" layout-padding>
<p>{{app.appId}}</p>
</div>
<div flex="20" layout-padding>
<p>{{app.appName}}</p>
</div>
</md-list-item>
</div>
this the angular service
app.service('AppManagerService',function($http){
this.loadApps = function(){
var request = $http.get('apps');
return request.then(handleSuccess,handleError);
};
this.submitApp = function(){
var request = $http.post('apps',
$('#newAppDetail').serialize(),
{headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
);
return request;
};
function handleError(responce){
console.log(responce);
}
function handleSuccess( response ) {
return response.data.value;
}
});
this the angular controller
app.controller('AppManagerCtrl', function($scope,$mdDialog,$mdMedia,AppManagerService) {
function loadApps(){
AppManagerService.loadApps().then(function(apps){
$scope.apps = apps;
console.log($scope.apps);
}
);
}
loadApps();
$scope.submitNewApp = function(){
AppManagerService.submitApp().then(function(responce){
var data = responce.data;
if(data.status == 1){
loadApps();
}
});
};
});
all these are in the html body.from the begin html part then angular service and finally controller.
The result of an ajax call isn't monitored by Angular, which is why your scope isn't updated (it will be on the digest though).
To solve this, you must manually call $scope.apply().
However, if another digest is already in progress, it will throw an error. So it's safer to use the $timeout utility:
function loadApps(){
AppManagerService.loadApps().then(function(apps){
$timeout(function() {
// update your scope variables here. The refresh will occur automatically.
$scope.apps = apps;
console.log($scope.apps);
});
});
}

Accessing first item in $resource.query() - Angularjs

I'm having some problems with the $resource.query() method. I'm trying to access the first element in it, but its not working for me. The selection controllers returns the collection without a problem.
controller.js
angular.module('bookshelf').controller('bsMainCtrl', function($scope, bsBooks){
var data = bsBooks.query();
$scope.singleBook = data[0];
});
angular.module('bookshelf').controller('bsSelectionCtrl', function($scope, bsBooks){
var booksData = bsBooks.query();
$scope.books = booksData;
});
main.jade
.singleBook
.selection
include selection
.content
include book-list
book-list.jade
div(ng-controller='bsMainCtrl')
p Title: {{ singleBook.title }}
p Author: {{ singleBook.author }}
p ISBN: {{ singleBook.ISBN }}
p Created at: {{ singleBook.createdAt | date }}
a(ng-href='/edit/{{ singleBook._id }}') Edit
selection.jade
div(ng-controller="bsSelectionCtrl")
div(ng-repeat='book in books')
button(ng-click='selectBook()') {{ book.title }}
service.js
angular.module('bookshelf').factory('bsBooks', function($resource) {
var BookshelfResource = $resource('/api/books/:_id', {_id: "#id" }, {
update: {method: 'PUT', isArray: false}
});
return BookshelfResource;
});
route.js
exports.getBooks = function(req, res){
Book.find({}).exec(function(err, collection){
res.send(collection);
});
};
Is it Angular $scope related? I have tried using the Angular inspector, but could only conclude that singleBook is null.
$resource.query() returns a promise, which contains no data initially, so you can't access it by numbered index at the point where you're attempting to.
Try instead:
bsBooks.query().$promise.then(function(data){
$scope.singleBook = data[0];
});
Demo
Use callback or promise for wait data from server
var data = bsBook.query(function(){
$scope.singleBook = data[0];
})
see here

adding more than one sources of data to angular

this is what I have in my model
// The contents of individual model .js files will be concatenated into dist/models.js
(function() {
// Protects views where angular is not loaded from errors
if ( typeof angular == 'undefined' ) {
return;
};
var module = angular.module('myModel', ['restangular']);
module.factory('myRestangular', function(Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl('http://localhost/data');
RestangularConfigurer.setRequestSuffix('.json');
RestangularConfigurer.setRestangularFields({
id: "my_id"
});
});
});
})();
this is fine. but now I have another json that I need to grab data from. How could I change this model to look for that other json as well. I am very very new to angular and still learning how model data binding works!
*This is what I have tired *
my model
var module = angular.module('FloorModel', ['restangular']);
module.factory('FloorRestangular', function(Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl('http://localhost/data/floor');
RestangularConfigurer.setRequestSuffix('.json');
RestangularConfigurer.setRestangularFields({
id: "floor_id"
});
});
});
**my controller**
myApp.controller('FloorCtrl', function ($scope, $filter, FloorRestangular) {
// Fetch all objects from the local JSON (see app/models/mdpocket.js)
FloorRestangular.all('floor').getList().then( function(floors) {
// Then select the one based on the view's id query parameter
$scope.floor = $filter('filter')(floors, {floor_id: steroids.view.params['id']})[0];
});
// -- Native navigation
steroids.view.navigationBar.show("Floor: " + steroids.view.params.id );
});
*my view *
<div ng-app="myApp">
<div ng-controller="FloorCtrl">
<div class="topcoat-list__container">
<ul class="topcoat-list">
<li class="topcoat-list__item" hm-tap="open(floor.floor_id)" ng-repeat="floor in floors">
Floor Name: {{ floor.name }}
</li>
</ul>
</div>
</div>
</div>

Resources