AngularJS: How to bind properties of an object to scope - angularjs

I am new to use AngularJS and I am an absolute beginner. I tried using filters. I tried binding to the properties instead of directly binding the object. But the code shows {{x.people}} as the output instead of showing the list. What am I missing out here?
<!DOCTYPE html>
<html>
<head>
<title>ANGULAR APP</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
</head>
<body ng-app="myApp" ng-controller="myFirstController">
<p>Type a letter in the input field:</p>
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in model.people">
{{ x.name }}
</li>
</ul>
</body>
<script>
var app = angular.module('myApp', []);
var myFirstController = function($scope) {
$scope.model = {
people: [{
name: 'Jani',
country: 'Norway'
},
{
name: 'Carl',
country: 'Sweden'
},
{
name: 'Margareth',
country: 'England'
},
{
name: 'Hege',
country: 'Norway'
},
{
name: 'Joe',
country: 'Denmark'
},
{
name: 'Gustav',
country: 'Sweden'
},
{
name: 'Birgit',
country: 'Denmark'
},
{
name: 'Mary',
country: 'England'
},
{
name: 'Kai',
country: 'Norway'
}
];
};
}
app.controller('myFirstController', myFirstController);
</script>
</html>

there is an unnecessary ; at the end of your json data:
$scope.model = {
people:[
... // your data
{name:'Kai',country:'Norway'}]; // <------ here the ; is illegal
};
}
refer below fixed example:
var app = angular.module('myApp', []);
var myFirstController = function($scope) {
$scope.model = {
people: [{
name: 'Jani',
country: 'Norway'
},
{
name: 'Carl',
country: 'Sweden'
},
{
name: 'Margareth',
country: 'England'
},
{
name: 'Hege',
country: 'Norway'
},
{
name: 'Joe',
country: 'Denmark'
},
{
name: 'Gustav',
country: 'Sweden'
},
{
name: 'Birgit',
country: 'Denmark'
},
{
name: 'Mary',
country: 'England'
},
{
name: 'Kai',
country: 'Norway'
}
]
};
}
app.controller('myFirstController', myFirstController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myFirstController">
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in model.people | filter: {name: test}">
{{ x.name }}
</li>
</ul>
</div>

Related

Table without using bootstrap in AngularJS

This is my angular js code
var app = angular.module('DemoApp', []);
app.controller('DemoController', function ($scope) {
$scope.name = [
{ Country: "India", Capital: "New Delhi" },
{ Country: "China", Capital: "Beijing" },
{ Country: "Japan", Capital: "Tokyo" },
{ Country: "France", Capital: "Paris" },
{ Country: "Russia", Capital: "Moscow" },
{ Country: "Nepal", Capital: "Kathmandu" },
{ Country: "England", Capital: "London" },
{ Country: "Belgium", Capital: "Brussels" },
{ Country: "Greece", Capital: "Athens" },
{ Country: "Portugal", Capital: "Lisbon" }]
});
I want to do without bootstrap
You can use a ng-repeat to create a table in angularjs. You can then style your table according to your requirements using css if you don't want to use bootstrap.
var app = angular.module('DemoApp', []);
app.controller('DemoController', function ($scope) {
$scope.countries = [
{ Country: "India", Capital: "New Delhi" },
{ Country: "China", Capital: "Beijing" },
{ Country: "Japan", Capital: "Tokyo" },
{ Country: "France", Capital: "Paris" },
{ Country: "Russia", Capital: "Moscow" },
{ Country: "Nepal", Capital: "Kathmandu" },
{ Country: "England", Capital: "London" },
{ Country: "Belgium", Capital: "Brussels" },
{ Country: "Greece", Capital: "Athens" },
{ Country: "Portugal", Capital: "Lisbon" }]
});
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.js"></script>
<title>Table</title>
</head>
<div ng-app="DemoApp" ng-controller="DemoController">
<table>
<tr><th>{{ Country}}</th>
<th>{{ Capital }}</th></tr>
<tr ng-repeat="x in countries">
<td>{{ x.Country }}</td>
<td>{{ x.Capital }}</td>
</tr>
</table>
</div>

How to filter multiple JSON Data with AngularJs?

My JSON file
{
records: [
{
Name: "Alfreds Futterkiste",
City: "Berlin",
Country: "Germany"
},
{
Name: "Ana Trujillo Emparedados y helados",
City: "México D.F.",
Country: "Mexico"
},
{
Name: "Antonio Moreno Taquería",
City: "México D.F.",
Country: "Mexico"
},
{
Name: "Around the Horn",
City: "London",
Country: "UK"
}
]
}
How can I filter only name of user with Country: "Mexico" or "Germany" with AngularJS ?
If you care about performance you should better no use $filter provider. Instead you should go for a custom code.
You should better maintain a list of filtered records.
<div ng-controller="AppController as app">
<label ng-repeat="country in app.availableCountries track by $index">
<input type="checkbox" ng-model="country.selected" ng-click="app.filterByCountries()"> {{country.name}}
</label>
<h2>Filtered Records</h2>
<div ng-repeat="record in app.filteredRecords">
{{record | json}}
</div>
</div>
And perform filtering functionality in your controller.
angular.module('app', [])
.controller("AppController", function() {
this.records = [{
Name: "Alfreds Futterkiste",
City: "Berlin",
Country: "Germany"
}, {
Name: "Ana Trujillo Emparedados y helados",
City: "México D.F.",
Country: "Mexico"
}, {
Name: "Antonio Moreno Taquería",
City: "México D.F.",
Country: "Mexico"
}, {
Name: "Around the Horn",
City: "London",
Country: "UK"
}];
this.filteredRecords = [];
this.availableCountries = _.uniq(this.records.map(record => record.Country)).map(country => {
return {
name: country
}
});
this.filterByCountries = () => {
const lowerCaseCountries = this.availableCountries.filter(country => country.selected).map(country => country.name.toLowerCase());
if (!lowerCaseCountries.length) {
this.filteredRecords = angular.copy(this.records);
return;
}
this.filteredRecords = angular.copy(this.records.filter(record => lowerCaseCountries.includes(record.Country.toLowerCase())));
}
this.filterByCountries();
})
Here's a working fiddle demonstrating your case. Feel free to ask anything.
Try this ..
var app = angular.module('myapp', []);
app.controller('myctrl', function($scope) {
$scope.data = records: [
{
Name: "Alfreds Futterkiste",
City: "Berlin",
Country: "Germany"
},
{
Name: "Ana Trujillo Emparedados y helados",
City: "México D.F.",
Country: "Mexico"
},
{
Name: "Antonio Moreno Taquería",
City: "México D.F.",
Country: "Mexico"
},
{
Name: "Around the Horn",
City: "London",
Country: "UK"
}
];
$scope.filteredData = $scope.data.filter(function(d) {
return d.Country === 'Mexico' || d.Country === 'Germany'
});
});

How to make controller to work in a custom directive?

i am working with angularjs.The problem is that i wrote a controller in directive after a compile function and the output through the compile function is shown as that in the pic. i.e "first in the compile". but the output from the controller is not showing and it's showing an error and the error is displayed in the image i have posted. please help me with this.
am sending the code
var app = angular.module("myapp", []);
app.controller('ctrl', ['$scope', function ($scope) {
$scope.emp = [{ name: "Day", age: "25", salary: "30000", place: "sydney", color: "#FF5733" },
{ name: "Dickinson", age: "34", salary: "6000", place: "disney", color: "#FAB304" },
{ name: "Domeyko", age: "27", salary: "9000", place: "newyork", color: "#0ED1B3" },
{ name: "Echols", age: "25", salary: "15000", place: "sweden", color: "#896BBB" },
{ name: "Echols", age: "25", salary: "15000", place: "sweden", color: "#387037" },
{ name: "Echols", age: "25", salary: "15000", place: "sweden", color: "#F3AE1B" },
{ name: "Echols", age: "25", salary: "15000", place: "sweden", color: "#FAB304" },
{ name: "Echols", age: "25", salary: "15000", place: "sweden", color: "#D10E7B" },
{ name: "Echols", age: "25", salary: "15000", place: "sweden", color: "#0EC8D1" },
{ name: "Echols", age: "25", salary: "15000", place: "sweden", color: "#FFC300 " },
{ name: "Echols", age: "25", salary: "15000", place: "sweden", color: "#D10E5B" },
{ name: "Echols", age: "25", salary: "15000", place: "sweden", color: "#13D0E1" }];
}]);
app.directive('showDetails', function ($interpolate) {
return {
//templateUrl: 'showDetails.html'
compile: function (tElement, tAttributes) {
console.log(tAttributes.text + "-in compile");
},
controller: function ($scope, $element, $attri) {
var v = $interpolate($attri.text)($scope);
//console.log($attri.text + "-in controller");
console.log(v + "-in controller");
}
}
});
<script src="../Scripts/angular.min.js"></script>
<link href="../Content/bootstrap.css" rel="stylesheet" />
<script src="../Scripts/bootstrap.min.js"></script>
<script src="../js/app.js"></script>
<script src="../js/ChildCtrl.js"></script>
<!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>-->
</head>
<body style="background-image: url('../images/uRzTkNW.jpg');" ng-controller="ctrl">
<div ng-repeat="emps in emp" class="col-md-3">
<div show-details text="first">
</div>
</div>
</body>
</html>
Your problem is this line:
controller: function ($scope, $element, $attri) {
If you click on the link given in the error message it probably explains all this, but the problem is you are trying to inject a service called $attri into your controller but there is no angular service of that name: you probably wanted $attrs. $scope, $element, $attrs, $transclude are all available to inject into a controller as are other angular services.

Angular JS ng-repeater not populating 2D array data

I'm currently working on a test application. When i use the ng-repeater to populate the data, it is currently showing empty fields. However when i console.log the array, it is showing the correct data.
ORDER CONTROLLER
(function()
{
var injectParams = ['$stateParams'];
function orderController($stateParams) {
var vm = this;
var customerId = $stateParams.id;
customers = [
{
id: 1,
joined: '2000-12-02',
name: 'John',
city: 'Chandler',
orderTotal: 9.9956,
orders: [
{
id: 1,
product: 'Shoes',
total: 9.9956
}
]
},
{
id: 2,
joined: '1965-01-25',
name: 'Zed',
city: 'Las Vegas',
orderTotal: 19.99,
orders: [
{
id: 2,
product: 'Baseball',
total: 9.995
},
{
id: 3,
product: 'Bat',
total: 9.995
}
]
},
{
id: 3,
joined: '1944-06-15',
name: 'Tina',
city: 'New York',
orderTotal: 44.99,
orders: [
{
id: 4,
product: 'Headphones',
total: 44.99
}
]
},
{
id: 4,
joined: '1995-03-28',
name: 'Dave',
city: 'Seattle',
orderTotal: 101.50,
orders: [
{
id: 5,
product: 'Kindle',
total: 101.50
}
]
}
];
//load customers to view
vm.orders = [];
var result = customers;
function loadCustomers()
{
for (var i = 0; i < result.length; i++)
{
if (result[i].id == parseInt(customerId))
{
vm.orders.push(result[i].orders);
}
}
}
loadCustomers();
console.log(vm.orders);
};
orderController.$inject = injectParams;
angular.module('app')
.controller('orderController', orderController);
}());
ORDERS HTML
<div class="row">
<div class="small-12 columns">
<h1>ORDERS</h1>
<table>
<tr>
<th>ID</th>
<th>Product</th>
<th>Total</th>
</tr>
<tr ng-repeat="order in aT.orders">
<td>{{ order.id }}</td>
<td>{{ order.product }}</td>
<td>{{ order.total }}</td>
</tr>
</table>
</div><!--small-12 columns-->
</div><!--row-->
APP.JS
//Initialise Foundation
$(document).foundation();
//Initialise Module
(function ()
{
angular.module('app', ['ui.router'])
.config(function ($stateProvider, $urlRouterProvider)
{
$urlRouterProvider.otherwise('/customers');
$stateProvider
.state('customers',
{
url: '/customers',
templateUrl: 'app/views/customers.html',
controller: 'customerController',
controllerAs: 'aT',
})
.state('orders',
{
url: '/orders/:id',
templateUrl: 'app/views/orders.html',
controller: 'orderController',
controllerAs: 'aT',
});
});
}());
If orders is an array of arrays, you would need two repeaters. I'm not sure why you're pushing customer orders into orders as you seem to be searching by customer ID which appears to be unique among the items in customers. I would simply assign the value to orders, ie
var findCustomerOrders = function() {
for (var i = 0, l = customers.length; i < l; i++) {
if (customers[i].id == customerId) {
return customers[i].orders;
}
}
return [];
};
vm.orders = findCustomerOrders();
Your current template should be fine with this data.
You need to attach your array to scope
JS:
// declare a module
var app = angular.module('myApp', []);
// configure the module.
// in this example we will create a greeting filter
app.controller('CustomerController', ['$scope',
function($scope) {
$scope.customers = [
{
id: 1,
joined: '2000-12-02',
name: 'John',
city: 'Chandler',
orderTotal: 9.9956,
orders: [
{
id: 1,
product: 'Shoes',
total: 9.9956
}
]
},
{
id: 2,
joined: '1965-01-25',
name: 'Zed',
city: 'Las Vegas',
orderTotal: 19.99,
orders: [
{
id: 2,
product: 'Baseball',
total: 9.995
},
{
id: 3,
product: 'Bat',
total: 9.995
}
]
},
{
id: 3,
joined: '1944-06-15',
name: 'Tina',
city: 'New York',
orderTotal: 44.99,
orders: [
{
id: 4,
product: 'Headphones',
total: 44.99
}
]
},
{
id: 4,
joined: '1995-03-28',
name: 'Dave',
city: 'Seattle',
orderTotal: 101.50,
orders: [
{
id: 5,
product: 'Kindle',
total: 101.50
}
]
}
];
}
]);
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body ng-app="myApp">
<div ng-controller="CustomerController">
<div ng-repeat="customer in customers">
{{customer}}
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script src="scripts.js"></script>
</body>
</html>

How to pass list to angular array

I am a new to angular... I have an object list that I would like to pass to angular and use the ng-repeat function.
Using NameList that was passed from my controller, I would like to display a list of id-names-states. Before, I did the following...
<ul>
#foreach (var item in Model.NameList) {
<li>item.id - item.names - item.states</li> }
</ul>
the list would be something like...
id: '1', name: 'John Doe', city: 'Phoenix'
id: '2', name: 'Tony Hope', city: 'Queens'
id: '3', name: 'Jane Doe', city: 'Frederick'
id: '4', name: 'John Smith', city: 'Miami'
id: '5', name: 'Tom Ford', city: 'Atlanta'
After realizing angulars capabilities I would like to set up the list, with the ability to have the user filter based on names
So my question is, How do I pass the NameList object to get populated with angular, or can I just populate the object and tie the list to angular somehow?
This is what I have so far
<div id="angularWrapper" data-ng-app="" data-ng-controller ="SimpleController">
<div>Name:
<input type="text" data-ng-model="name" />
</div>
#*I would like to pass Model.NameList to customers*#
<div data-ng-model="#Model.NameList"></div>
<br />
<ul>
<li data-ng-repeat="cust in customers | filter:name">{{cust.id + - + cust.name + - + cust.state}}</li>
</ul>
</div>
In your controller:
$scope.customers = [
{ id: '1', name: 'John Doe', city: 'Phoenix' },
{ id: '2', name: 'Tony Hope', city: 'Queens' },
{ id: '3', name: 'Jane Doe', city: 'Frederick' },
{ id: '4', name: 'John Smith', city: 'Miami' },
{ id: '5', name: 'Tom Ford', city: 'Atlanta' }
];
I think you're confused about how AngularJS binding works, you should read the guide on Data Binding: http://docs.angularjs.org/guide/databinding
In the meantime here's a simple JSFiddle I think does what you're looking for: http://jsfiddle.net/mikeeconroy/75WPW/1/
<div ng-controller="myCtrl">
Name: <input type="text" ng-model="name" />
<ul>
<li ng-repeat="cust in customers | filter:name">{{cust.id}} - {{cust.name}} - {{cust.city}}</li>
</ul>
</div>
And the controller:
angular.module('myApp',[])
.controller('myCtrl', ['$scope','mySrv',function ($scope,mySrv) {
$scope.name = '';
$scope.customers = [];
$scope.customers = mySrv.getCustomers();
}])
// fake service, substitute with your server call ($http)
.factory('mySrv',function(){
var customers = [
{id: '1', name: 'John Doe', city: 'Phoenix'},
{id: '2', name: 'Tony Hope', city: 'Queens'},
{id: '3', name: 'Jane Doe', city: 'Frederick'},
{id: '4', name: 'John Smith', city: 'Miami'},
{id: '5', name: 'Tom Ford', city: 'Atlanta'}
];
return {
getCustomers : function(){
return customers;
}
};
});
You could also set $scope.customers by using the resolve function of your route.
I came up with a solution that may have a possible alternative...
<div id="angularWrapper" data-ng-app="demoApp" data-ng-controller="SimpleController">
<div>
Name:
<input type="text" data-ng-model="name" />
</div>
<div>
<ul>
<li data-ng-repeat="eg in List | filter: name">{{ eg.Name }}</li>
</ul>
</div>
<br />
<script>
$(function () {
var scope = angular.element('#angularWrapper').scope();
#foreach (var npo in Model.NameList)
{
#: scope.AddList({ Name: '#eg.Name' });
}
scope.$apply();
});
</script>
</div>
.js file
function getList() {
var self = this;
self.Name = "";
}
var demoApp = angular.module('demoApp', []);
demoApp.controller('SimpleController', SimpleController); //could just load the function($scope) from simplecontroller..
function SimpleController($scope) {
$scope.List = [];
$scope.AddList = function (data) {
var eg = new getList();
eg.Name = data.Name;
$scope.List.push(eg);
}
}

Resources