angularjs without controller ng-click not firing - javascript

I am practising angularjs. In below example, ng-click is not firing at all, not sure why. I actually not using any controller in my code, may be because of that, ng-click not firing?
index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="myApp1">
<div ng-init="users=[{name: 'john', city: 'NY', order: 10},{name: 'james', city: 'washington', order: 20},{name: 'william', city: 'seattle', order: 30}]">
<h2>Customers</h2>
Search Customer: <input type="text" ng-model="searchText" placeholder="search customer here">
<br><br>
<table border="2">
<thead>
<tr>
<th ng-click="orderByProperty('name')">Name</th>
<th ng-click="orderByProperty('city')">City</th>
<th ng-click="orderByProperty('order')">Order</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users | filter : searchText | orderBy : orderByProperty : true">
<td>{{user.name | uppercase}}</td>
<td>{{user.city}}</td>
<td>{{user.order | currency}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
app.js
var myApp1 = angular.module('myApp1',[])
function orderByProperty(propertyName){
// alert('dsfdf')
return propertyName;
}
Please tell me what went wrong in above code? Is that mandatory to use controller in a code? If not used, ng-click do not work at all?
UPDATE
When I replaced ng-click with 'onclick', even is getting fired, but sorting functionality is not working.
UPDATE2: BELOW IS THE UPDATED CODE
index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="myApp1">
<div ng-controller="MyController">
<div ng-init="users=[{name: 'john', city: 'NY', order: 10},{name: 'james', city: 'washington', order: 20},{name: 'william', city: 'seattle', order: 30}]">
<h2>Customers</h2>
Search Customer: <input type="text" ng-model="searchText" placeholder="search customer here">
<br><br>
<table border="2">
<thead>
<tr>
<th ng-click="orderByProperty('name')">Name</th>
<th ng-click="orderByProperty('city')">City</th>
<th ng-click="orderByProperty('order')">Order</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users | filter : searchText | orderBy : orderByProperty : true">
<td>{{user.name | uppercase}}</td>
<td>{{user.city}}</td>
<td>{{user.order | currency}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
app.js
var myApp1 = angular.module('myApp1',[])
myApp1.controller('MyController', ['$scope', function($scope){
$scope. orderByProperty = function(propertyName){
// alert('dsfdf')
return propertyName;
}
}])
Above I used controller, now evenT gets firing but sorting not working as expected..

Yes you need to have the ng-controller placed in order to get ng-click work.
When a controller is attached to the DOM via the ng-controller
directive, Angular will instantiate a new controller object, using the
specified controller's constructor function. A new child scope will be
available as an injectable parameter to the controller's constructor
function as $scope.
Read more on controller

As #Sajeetharan said, in angularjs all functions you call need to be declared in controllers, that is how it works

before using ng-click u must place ng-controller in your HTML.
<body ng-app="myApp1" ng-controller="myAppCtrl">
var myApp1 = angular.module('myApp1',[]);
myApp1.controller('myAppCtrl',['$scope',function ($scope) {
$scope.orderByProperty=function(propertyName){
// alert('dsfdf')
return propertyName;
}
}]);

To make it work, 2 places need to change:
Binding orderBy with a ng-model value.
var myApp1 = angular.module('myApp1',[])
myApp1.controller('MyController', ['$scope', function($scope){
$scope. orderByProperty = function(propertyName){
$scope.myorder = propertyName;
}
}])
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="myApp1">
<div ng-controller="MyController">
<div ng-init="users=[{name: 'john', city: 'NY', order: 10},{name: 'james', city: 'washington', order: 20},{name: 'william', city: 'seattle', order: 30}]">
<h2>Customers</h2>
Search Customer: <input type="text" ng-model="searchText" placeholder="search customer here">
<br><br>
<table border="2">
<thead>
<tr>
<th ng-click="orderByProperty('name')">Name</th>
<th ng-click="orderByProperty('city')">City</th>
<th ng-click="orderByProperty('order')">Order</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users | filter : searchText | orderBy : myorder : true">
<td>{{user.name | uppercase}}</td>
<td>{{user.city}}</td>
<td>{{user.order | currency}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

Related

angularjs ng-table/ng-repeat rows not loading

I am trying to follow the tutorial Here on using ng-Table. If I download the whole example from Git then it loads fine but trying to follow even the simplest example myself then the Column headers and filters load but there are no rows? If I add another row in the HTML manually it does appear so the issue seems to either be with the data binding or the ng-repeat. There are no errors showing in the console.
Example Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-resource.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-route.js"></script>
<link rel="stylesheet" ; href="https://unpkg.com/ng-table#4.0.0/bundles/ng-table.css">
<script src="https://unpkg.com/ng-table#4.0.0/bundles/ng-table.js"></script>
</head>
<body>
<div ng-app="MyApp" ng-controller="MyCtrl">
<table ng-table="vm.tableParams" class="table" show-filter="true">
<tr ng-repeat="user in $data">
<td title="'Name'" filter="{ name: 'text'}" sortable="'name'">
{{user.name}}
</td>
<td title="'Age'" filter="{ age: 'number'}" sortable="'age'">
{{user.age}}
</td>
</tr>
</table>
</div>
<script>
var app = angular.module("MyApp", ["ngTable"]);
app.controller('MyCtrl', function ($scope, NgTableParams) {
var self = this;
var data = [{ name: "Moroni", age: 50 } /*,*/];
self.tableParams = new NgTableParams({}, { dataset: data });
});
</script>
</body>
</html>
You haven't specified your controller reference.
Change the code to <div ng-app="MyApp" ng-controller="MyCtrl as vm"> and it will work as you expect it.
Working example: http://codepen.io/DeividasK/pen/qrWqey?editors=1010
You didn't assign your object in scope
try this below code instead of your code
app.controller('MyCtrl', function ($scope, NgTableParams) {
var self = this;
self.data = [{ name: "Moroni", age: 50 } /*,*/];
self.tableParams = new NgTableParams({}, { dataset: self.data });
});
This is ng table, the problem is you are using the controller as vm, just remove the vm or put controller as vm and it's work.
<table ng-table="tableParams" class="table" show-filter="true">
<tr ng-repeat="user in $data">
<td title="'Name'" filter="{ name: 'text'}" sortable="'name'">
{{user.name}}
</td>
<td title="'Age'" filter="{ age: 'number'}" sortable="'age'">
{{user.age}}
</td>
</tr>
</table>

What's the meaning of sortBy in ng-click?

I'm pretty new in AgularJS, and when I tried to do the practice:
JS file:
function CustomersController() {
this.sortBy = 'name';
this.reverse = false;
this.customers= [{joined: '2000-12-02', name:'John', city:'Chandler', orderTotal: 9.9956}, {joined: '1965-01-25',name:'Zed', city:'Las Vegas', orderTotal: 19.99},{joined: '1944-06-15',name:'Tina', city:'New York', orderTotal:44.99}, {joined: '1995-03-28',name:'Dave', city:'Seattle', orderTotal:101.50}];
this.doSort = function(propName) {
this.sortBy = propName;
this.reverse = !this.reverse;
};
}
HTML file:
<!doctype html>
<html ng-app="customersApp">
<head>
<title>Iterating Over Data</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body ng-controller="CustomersController">
<h2>Customers</h2>
Filter: <input type="text" ng-model="customerFilter.name" />
<br /><br />
<table>
<tr>
<th ng-click="doSort('name')">Name</th>
<th ng-click="doSort('city')">City</th>
<th ng-click="doSort('orderTotal')">Order Total</th>
<th ng-click="doSort('joined')">Joined</th>
</tr>
<tr ng-repeat="cust in customers | filter:customerFilter | orderBy:sortBy:reverse">
<td>{{ cust.name }}</td>
<td>{{ cust.city }}</td>
<td>{{ cust.orderTotal | currency }}</td>
<td>{{ cust.joined | date }}</td>
</tr>
</table>
<br />
<span>Total customers: {{ customers.length }}</span>
<script src="angular.js"></script>
<script src="app/app.js"></script>
<script src="app/controllers/customersController.js"></script>
</body>
</html>
On the webpage I can click the table's head and sort by name. So I want to know that what's the meaning of sortBy ? Is it a built-in variable in $scope? I tried to change its name (like "sortby") and it doesn't sort (just reverse). If it is, where could I find the built-in functions of $scope? Thanks a lot!
First of all sortBy is just the name of the variable and is not built into the $scope. You could use anything. Notice that sortBy is referenced in 2 places:
In the HTML:
<tr ng-repeat="cust in customers | filter:customerFilter | orderBy:sortBy:reverse">
And in your controller in 2 places:
// This initializes the sort order
this.sortBy = 'name';
// This sets the new sort order when a user clicks on the table heding
this.sortBy = propName;
You are free to use another name for sortBy, you just need to replace it in all of those places.
However, orderBy is specific to the ng-repeat, so you can't change that name. For more information you can check out the last example on this page:
https://docs.angularjs.org/api/ng/directive/ngRepeat

Using orderBy filter dynamically in AngularJS

Trying to enter ordering criteria from input box and order the content dynamically. The code works fine as it is, but when I try to change:
orderBy:'age'
with
orderBy:'{{criteria}}'
it doesn't work.
Here is the code:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="testApp" ng-controller="testController">
<p>Enter ordering criteria in the input box:</p>
<p><input type="text" ng-model="criteria"></p>
<p>{{criteria}}</p>
<table class="friend">
<tr>
<th>Name</th>
<th>Phone Number</th>
<th>Age</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:'age'">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('testApp',[]);
app.controller('testController', ['$scope', function($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}];
}]);
</script>
</body>
</html>
{{}} is only for interpolation in non angular expressions. Since ng-repeat is executed against the scope, you can just reference the variable directly.
orderBy:criteria
I'm assuming that you are wanting to filter your list with the text box and order the result by the age property of each object? If you wish to do this, you'd just chain filters.
<tr ng-repeat="friend in friends | orderBy:'age' | filter : criteria">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
Here is a plunker with an example of using multiple filters
http://plnkr.co/edit/8rfitXitGhjjthUXujOL?p=info

Can't bind 2 objects from JSON in Angularjs?

I'm new to Angularjs. I am learning about factory.
In my example, I have 2 requests to Restful Api and got 2 responses in JSON format.
With the first json, I can use ng-repeat to show them but the 2nd json can't bind to the view.
How can I bind both responses into the same view?
this is my code
index.html file
<!DOCTYPE html>
<html lang="en" ng-app='f1feed'>
<head>
<title>AngularJS Routing example</title>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
padding-top: 10px;
background-color: #F5F5F5;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-route.min.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-controller="DriverController">
<table>
<thead>
<tr>
<th colspan="4">Drivers Champion Standings</th>
</tr>
<tr>
<th>No.</th>
<th>Full name</th>
<th>Driver ID</th>
<th>Points</th>
</tr>
</thead>
<tbody ng-repeat="driver in drivers">
<tr>
<td>{{$index + 1}} </td>
<td>{{driver.Driver.givenName}} {{driver.Driver.familyName}}</td>
<td>{{driver.Driver.driverId}}</td>
<td>{{driver.points}}</td>
</tr>
</tbody>
</table>
<div class="info">
<h1>1st Driver Detail info</h1>
<ul>
<li>Driver ID: {{alonso.driverId}} </li>
<li>Date of Birth: {{alonso.dateOfBirth}} </li>
<li>Nationality: {{alonso.nationality}}</li>
</ul>
</div>
</body>
</html>
file app.js
var app = angular.module('f1feed',[]);
app.factory('DriverSev', function($http){
var driverApi = {};
driverApi.getDriverStands = function(){
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/current/driverStandings.json?callback=JSON_CALLBACK'
});
};
driverApi.getDetail = function(){
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/drivers/alonso.json?callback=JSON_CALLBACK'
});
};
return driverApi;
});
app.controller('DriverController', function DriverController($scope, DriverSev){
$scope.drivers = [];
$scope.alonso = [];
DriverSev.getDriverStands().success(function(data){
$scope.drivers = data.MRData.StandingsTable.StandingsLists[0].DriverStandings;
})
DriverSev.getDetail().success(function(data){
$scope.alonso = data.MRData.DriverTable.Drivers;
console.log($scope.alonso);
})
});
Thanks
your $scope.alonso is unused in your view put it in another ng-repeat to display it
<table>
<thead>
<tr>
<th colspan="4">Drivers Champion Standings</th>
</tr>
<tr>
<th>No.</th>
<th>Name</th>
</tr>
</thead>
<tbody ng-repeat="alon in alonso">
<tr>
<td>{{$index + 1}} </td>
<td>{{alon}}</td>
</tr>
</tbody>
</table>
if it's the same data model, push it in $scope.drivers
$scope.alonso is an array.
<ANY ng-repeat="details in alonso">
<any>Driver ID: {{details.driverId}} </any>
<any>Date of Birth: {{details.dateOfBirth}} </any>
<any>Nationality: {{details.nationality}}</any>
</ANY>
should do the trick, or something ugly such as {{alonso[0].driverId}}

Angular JS passing ng-repeat $index as parameter

The following bit of code has a shell page index.html and a partial view (which is currently being used by two different controllers). The hard-coded data in AppController is wired into the list.html partial view and rendered as a table. In the JS I added a console.log to see when the controllers were being invoked. When the app loads up
AppController fires, when I invoke #/new, NewController fires. However, when I click on the edit button which is next to each row, the EditController isn't being called. EditController should use the /partials/edit.html view but populate the fields with the information of the row that was clicked on. So crew[0] in this example is Picard and his data should be pre-populated when you click on that icon. I'm not getting any errors, but the EditController's view isn't being injected when it should be.
JS
angular.module('enterprise', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when("/", { templateUrl: "/partials/list.html" })
.when("/new", { templateUrl: "/partials/edit.html", controller: "NewController" })
.when("/edit:id", { templateUrl: "/partials/edit.html", controller: "EditController" });
})
//this is the that iterated over in the partial views ng-repeat
function AppController($scope){
$scope.crew = [
{ name: 'Picard', description: 'captain' },
{ name: 'Riker', description: 'number 1' },
{ name: 'Word', description: 'Security' }
];
console.log('app controller hit');
}
function NewController($scope, $location) {
$scope.person = { name: "", description: "" };
$scope.save = function () {
$scope.crew.push($scope.person);
$location.path("/");
}
console.log('new controller hit');
}
function EditController($scope, $location,$routeParams) {
$scope.person = $scope.crew[$routeParams.id];
console.log('edit controller hit');
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>Angular JS Routing</title>
<link rel="stylesheet"
href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"/>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css"
rel="stylesheet">
</head>
<body>
<div ng-app="enterprise" ng-controller="AppController">
<h2>Enterprise Crew</h2>
<ng-view></ng-view>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
list.html
<table class="table table-striped" style="width: 250px">
<thead>
<tr>
<td>Name</td>
<td>Description</td>
<td> <i class="glyphicon glyphicon-plus-sign"></i>
</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in crew">
<td>{{person.name}}</td>
<td>{{person.description}}</td>
<td><i class="glyphicon glyphicon-edit"></i></td>
as ng-repeat loops through I'm trying to go to the edit.hml partial view and populate the text boxes in `edit.html` with the data from the row that was clicked on
</tr>
</tbody>
</table>
edit.html
<form action="">
<input ng-model="person.name"/ placeholder="Enter the person name">
<input ng-model="person.description"/ placeholder="Enter the description">
<button ng-click="save()" class="btn-primary">Save</button>
</form>
I'm not getting any errors, but my EditController is never being fired. Can someone let me know why? Thanks.
"/edit:id" should instead be "/edit/:id" in
.when("/edit:id", { templateUrl: "/partials/edit.html", controller: "EditController" });

Categories

Resources