I do not understand why ng-options is not populating the dropdown menu. JSON data is being returned from the service. I can console.log the data in the controller. So, why is ng-options not populating the dropdown
<tr class="info">
<td class = "col-xs-3">Maximum page size: </td>
<td class = "col-xs-9" ng-controller = "converseController"> Show conversations per page
<select ng-model = "selectedNumber" ng-options="conversation for conversation in conversations">
<option value = ""> Choose the number of conversations </option>
</select>
<aside id = "pageSize"> Show contacts per page
<select>
<option> 20 </option>
</select>
</aside>
</td>
</tr>
converse.js - Controller
(function() {
'use strict';
var converseController = function (getData, $scope) {
var url = '../../data/conversation.json';
getData.fetchData(url)
.then(function(data){
$scope.coversations = data.conversation;
console.log($scope.coversations);
});
};
angular.module('assignment3App')
.controller ('converseController', ['getData', '$scope', converseController]);
}());
conversation.json
{
"conversation": [
10,
20,
30,
40,
50,
60,
70,
80,
90,
100
]
}
Service - promise.js
(function() {
'use strict';
var getData = function (fetchDataService) {
this.fetchData = function(filePath) {
return fetchDataService.getContent(filePath)
.then(function (returnedData) {
return returnedData.data;
});
};
};
angular.module('assignment3App')
.service ('getData', ['fetchDataService', getData]);
}());
Service - callJson.js
(function() {
'use strict';
var fetchDataService = function($http) {
this.getContent = function(path) {
return $http({
method : 'get',
url : path
});
};
};
angular.module('assignment3App')
.service ('fetchDataService', fetchDataService);
}());
You are assinging the array to the wrong scope variable. $scope.coversations = data.conversation; should be spelt $scope.conversations = data.conversation;.
Related
I'm trying to get data from a Web API and display it in a table, but it doesn't work.
I am new to angularjs and i code simple program to get data from the Web API and display in table.but i am not able to get data.
Module
var app = angular.module("myApp", []);
Service
app.service("myService", function ($http) {
//get All Eployee
this.getEmployees = function () {
return $http.get('http://apidemo.gouptechnologies.com/api/admin');
};
})
Controller
app.controller("myCntrl", function ($scope, myService) {
$scope.divEmployee = false;
GetAllEmployee();
function GetAllEmployee() {
alert('home');
var getData = myService.getEmployees();
getData.then(function (emp) {
$scope.employees = emp.data;
}, function () {
alert('Error in getting records');
});
}
});
The JS code is included in the head tag of the HTML file.
HTML body
<body>
<div ng-app="myApp" ng-controller="myCntrl">
<ul>
<li ng-repeat="x in employees">
{{ x.username + ', ' + x.password }}
</li>
</ul>
</div>
</body>
The API URL is legitimate.
Thanks.
Let example a json file in "data/branchList.json" directory, And i am trying to access all data from json file using $http.
It may help you to call a rest service aslo. check this example
data/branchList.json
[
{
"branch_id": 1,
"branch_name": "Mummbai",
"branch_address": "India"
},
{
"branch_id": 2,
"branch_name": "New York",
"branch_address": "US"
}
]
Controller
angular.module('myApp')
.controller('myCntrl', ['$http', '$state', function ($http, $state) {
'use strict';
var vm = this;
function init(){
vm.branchs = '';
loadBranch();
}
init();
function loadBranch(){
$http.get('data/branchList.json').success(function(response){
vm.branchs = response;
})
}
}]);
In this example i am storing all the data in vm.branches variable, you can use this variable in html page
HTML
<li class="col-sm-6" ng-repeat = "branch in vm.branchs">
<strong>{{branch.branch_name}}</strong>
<span>{{branch.branch_address}}</span>
</li>
I have a simple controller in AngularJS, and i would like it to have 2 different functions :
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function($scope, $http, $log) {
//1st function
$scope.search = function() {
$http.post('server.php', { "data" : $scope.keywords})
.success(function(data, status) {
$scope.result = data;
})
};
//2nd function
$scope.tableClick = function() {
$log.log('Hello World!');
};
})
I think there's an issue somewhere in the syntax because this script works only when i remove the 2nd function.
When i use the script with the 2 functions (so, what i posted), i get {{ x }} for the following html elements :
<tr ng-repeat="x in result">
<td><a href="wwww.test.com" >{{ x }}</a></td>
Any clues ?
As I said in the comments, there's no echo 'Hello World!' in javascript. If you want to write that phrase on the DOM, then you have to use it as a simple expression. Just like:
$scope.helloWorld = 'Hello World!';
and then in the HTML you simply call it like {{helloWorld}}.
I'm seeing you're testing it with a function. In this case you should return the string 'Hello World!' like
$scope.helloWorld = function () {
return 'Hello World';
};
In the HTML:
{{ helloWorld() }}
In the case you want to simply "log" the Hello World! to the browser's console (which I doubt because you're not paying attention to JS errors): DO NOT USE console.log();. Use AngularJS' built-in service $log instead
A better code
Anyway, if I were you, I'd write that code differently. See
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function ($scope, $http, $log) {
//1st function
$scope.search = function () {
$http.post('server.php', { "data" : $scope.keywords })
.then(function (resp) { //use then instead of success/error
return resp.data;
}, function inCaseOfErrors (err) { //named just for teaching purposes
$log.log(err);
});
};
//2nd function
$scope.tableClick = function () {
$log.log('Hello World!');
};
})
Please make sure that your $scope.result has the right values. Also note that echo doesn't exist in javascript.
In the code below, I took away the server-call and used hard-coded data, just to test:
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function($scope, $http) {
$scope.result = ["apple", "orange", "raisin", "banana"];
//1st function
$scope.search = function() {
//$http.post('server.php', { "data" : $scope.keywords})
//.success(function(data, status) {
//$scope.result = data;
//})
};
//2nd function
$scope.tableClick = function(item) {
console.log("someone clicked the table! Row: " + item);
};
})
Html:
<table>
<tr ng-repeat="item in result">
<td data-ng-click="tableClick(item)">{{ item }}</td>
</tr>
</table>
Following are my questions on the code described below -
On page load, my below custom sort filter is getting called multiple times. why?
On selecting a select option (from directive), I want to trigger filter based on selected value (using two way binding). Here again filter is being called thrice. Why?
Can some one point me to answers? I know that Angular does a Dirty Check by comparing old and new digest, but why multiple and 3rd invocation (as mentioned in the above questions).
I have below directive -
angular.module("customDirectives", [])
.directive("sortAll", function () {
return {
restrict: "E",
scope: {
columns: "=sortcolumns",
optionselected: "=selectedoption"
},
templateUrl: '../Views/Directives/SortAll.html',
controller: function ($scope) {
$scope.sortOptions = [];
var asc = 'Ascending';
var desc = 'Descending';
$scope.getSortOptions = function () {
angular.forEach($scope.columns, function (item) {
$scope.sortOptions.push({ name: item + '-' + asc, value: asc });
$scope.sortOptions.push({ name: item + '-' + desc, value: desc });
});
$scope.optionselected = $scope.sortOptions[1];
return $scope.sortOptions;
}
}
};
});
Directive HTML -
<select name="sortOptions" id="sortOptions" class="form-control width-20percent pull-right"
ng-options="option.name for option in sortOptions"
ng-init="getSortOptions()"
ng-model="optionselected"></select>
And below Filter -
angular.module("customFilters", [])
.filter("sort", function ($filter) {
return function (data, sortOption) {
console.log(sortOption);
if (angular.isArray(data) && angular.isObject(sortOption)) {
var options = sortOption["name"].split('-');
var xc = options[1] == 'Ascending' ? false : true;
return $filter("orderBy")(data, options[0], xc);
} else {
return [];
}
}
});
Now my Controller code -
angular.module("productStore")
.controller("ProductListCtrl", function ($scope, $filter) {
});
And the main controller which gives the data -
angular.module("productStore")
.constant("dataUrl", "http://localhost:57398/testdata/Products.json")
.constant("productColumns", ["name","price","description"])
.controller("MainCtrl", function ($scope, $http, dataUrl, productColumns) {
$scope.data = {};
$scope.productColumns = productColumns;
$http.get(dataUrl)
.success(function (products) {
$scope.data.products = products;
})
.error(function (error) {
$scope.data.error = error;
})
});
HTML -
<body ng-controller="MainCtrl">
<div class="navbar navbar-inverse">
<a class="navbar-brand" href="#">PRODUCT STORE</a>
</div>
<div class="panel-default" ng-controller="ProductListCtrl" ng-hide="data.error" ng-cloak>
<div class="col-xs-8">
<sort-All sortcolumns="productColumns" selectedoption="selectedSortOption"></sort-All>
<div class="well padding-top-0px" ng-repeat="product in data.products | sort:selectedSortOption">
<h3>
<strong>{{product.name}}</strong>
<span class="pull-right label label-primary">
{{product.price | currency}}
</span>
</h3>
<span class="lead">{{product.description}}</span>
</div>
</div>
</div>
</body>
Sample Data -
[{
"category": "Watersports",
"description": "A boat for one person",
"name": "Kayak",
"price": 275,
"id": "05af70919155f8fc"
}]
On Page load -
On changing item in select -
I have two Models named "Jeans" and "Shirts"
which have two variables "name" and "color"
I want to have a search page in which user can search through database to find shirts and jeans in specific color or name.
This link might be a hint but I just could not figure it out
Similar Problem
I have got something here But it does not work.
I appreciate if you tell me how to fix it.Thanks!
View
<section data-ng-controller="AllsController" data-ng-init="find()">
<div class="page-header">
<h1>Alls</h1>
</div>
<div class="Search">
<h2>Search Section</h2>
<select data-ng-model="search1" id="search">
<option value="Model1">Jeans</option>
<option value="Model2">Shirts</option>
</select>
<select data-ng-model="search2" id="search">
<option value="Model1">Jeans</option>
<option value="Model2">Shirts</option>
</select>
<select data-ng-model="variable1" id="variable1">
<option selected="selected">AnyThing</option>
<option value="color1">Blue</option>
<option value="color2">Red</option>
</select>
<select data-ng-model="variable2" id="variable2">
<option selected="selected">AnyThing</option>
<option value="name1">John</option>
<option value="name2">Bob</option>
</select>
</div>
<br></br><br></br>
<h2>Result Section</h2>
<div class="list-group">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Color</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="all in alls">
<td data-ng-bind="all.name"></td>
<td data-ng-bind="all.color"></td>
</tr>
</tbody>
</table>
</div>
In controller; first I see which properties user has selected and assign it to FindArray
Then I see in which model user want to search.(AnyThing means that user has not selected anything)
Server Side Controller
exports.list = function(req, res) {
if (variable1 === "AnyThing")
{
if (variable2 === "AnyThing")
{
FindArray = {};
}else
{
FindArray = { name = variable2 };
}
}else
{
FindArray = { color = variable1 , name = variable2 };
}
if (req.body.search1 === 'Jeans')
{
if (req.body.search2 === 'Shirts')
{
Jeans.find(FindArray).sort('-created').populate('user', 'displayName').exec(function(err, jeans) {
Shirt.find(FindArray).sort('-created').populate('user', 'displayName').exec(function(err, shirts) {
var all = shirts.concat(jeans);
res.jsonp(all);
});
});
}else{
Jeans.find(FindArray).sort('-created').populate('user', 'displayName').exec(function(err, jeans) {
res.jsonp(jeans);
});
}
}else{
Shirt.find(FindArray).sort('-created').populate('user', 'displayName').exec(function(err, shirts) {
res.jsonp(shirts);
});
}
};
$Resource Service:
angular.module('alls').factory('Alls', ['$resource',
function($resource) {
return $resource('alls/:allId', { allId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}]);
Client Side Controller
angular.module('alls').controller('AllsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Alls', 'Jeans', function($scope, $stateParams, $location, Authentication, Alls, Jeans) {
$scope.find = function() {
$scope.search1 = search1;
$scope.search2 = search2;
$scope.variable1 = variable1;
$scope.variable2 = variable2;
$scope.alls = Alls.query();
};
}]);
Server Side Route
module.exports = function(app) {
var alls = require('../../app/controllers/alls.server.controller');
app.route('/alls').get(alls.list);
};
Preliminary review of this looks to me like your route is expecting a get, but your $resource is running a put. I'm also thinking that all of your scope assignments aren't going to work because you're assigning non existent variables.
Problem Question -
I have a two drop down in my view. And second drop down rely on the first one. But somehow second one does not get updated
// my firstdrop down
<select ng-controller="myController"
ng-options="customer.name for customer in customerDetailData" ng-model="customer"
ng-change="updateCost(customer)">
<option value="">Please select customer</option>
</select>
// my second drop down
<select ng-controller="myController"
ng-options="cc.name for cc in customerCostData">
<option value="">Please select cost</option>
</select>
// my controller
(function() {
var myController = function($scope,Service){
$scope.customerDetailData;
Service.cust()
.success(function(data){
console.log(data)
$scope.customerDetailData = data;
})
.error(function(status,error){
})
$scope.customerCostData;
$scope.updateCost=function(customer){
Service.cost(customer.id)
.success(function(cost){
$scope.customerCostData= cost
})
.error(function(status,data){
console.log(status);
console.log(data);
})
}
};
myController .$inject = ['$scope','Service'];
angular.module('app').controller('myController ',myController );
}());
Is anything i am missing ? the data is coming through fine in the console. Please guide me
There are 2 things to do here:
The first and main issue is that you are attaching ng-controller to each select individually. This means it is actually creating 2 separate controllers, one for each select, and so they are given different scopes. You need to apply the ng-controller attribute to a parent element, such as the form.
The second issue is that angular will not automatically update an element just because the scope variable is used in ng-options. You therefore need to give it a ng-model so that Angular watches it correctly.
Here is an example of the code with two separate controller instances. Note the 2 alerts:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<form ng-app="myApp">
<select ng-controller="myController"
ng-options="customer.name for customer in customerDetailData" ng-model="customer"
ng-change="updateCost(customer)">
<option value="">Please select customer</option>
</select>
<select ng-controller="myController"
ng-options="cc.name for cc in customerCostData" ng-model="customercustomerCostData">
<option value="">Please select cost</option>
</select>
</form>
<script type="text/javascript">
(function () {
var myApp = angular.module('myApp', []);
var myController = function ($scope) {
alert('myController created');
$scope.customerDetailData = [{ id: 1, name: "bob" }, { id: 2, name: "fred" }];
$scope.updateCost = function (customer) {
$scope.customerCostData = [{ name: customer.id.toString() }, { name: 'x' }];
}
};
myController.$inject = ['$scope'];
myApp.controller('myController', myController);
}());
</script>
Here it is with the single ng-controller applied to the form and ng-model="customerCostData" on the second select, so it now works:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<form ng-app="myApp" ng-controller="myController">
<select
ng-options="customer.name for customer in customerDetailData" ng-model="customer"
ng-change="updateCost(customer)">
<option value="">Please select customer</option>
</select>
<select
ng-options="cc.name for cc in customerCostData" ng-model="customercustomerCostData">
<option value="">Please select cost</option>
</select>
</form>
<script type="text/javascript">
(function () {
var myApp = angular.module('myApp', []);
var myController = function ($scope) {
alert('myController created');
$scope.customerDetailData = [{ id: 1, name: "bob" }, { id: 2, name: "fred" }];
$scope.updateCost = function (customer) {
// would be an ajax call
$scope.customerCostData = [{ name: customer.id.toString() }, { name: 'x' }];
}
};
myController.$inject = ['$scope'];
myApp.controller('myController', myController);
}());
</script>
is the cost data the result of an Ajax request? if so, you may need to force a force a $digest cycle to let the UI know the model has been changed. You can achieve this by wrapping the assignment of cost in a $timeout, or $apply.
$timeout(function () {
$scope.customerCostData = cost;
});
or
$scope.$apply(function () {
$scope.customerCostData = cost;
});