Can't retrieve data from controller AngularJS - angularjs

I am learning AngularJS (so I'm a noob to this) I'm following a tutorial on Udemy. I even looked at the docs and have tried the wiring they have presented. I just can't seem to get the customers data in the table. What am I doing wrong and an explanation would be appreciated so I can learn the right way of AngularJS for the interview? Any help is much appreciated. By the way I'm using the latest version of AngularJS 1.7
(function () {
var CustomersController = function($scope) {
$scope.sortBy = 'name';
$scope.reverse = false;
$scope.customers = [{name:'sanjeet', joined:'2000-12-02', orderTotal: 10.096, age: 26}, {name:'gurpreet', orderTotal:201.961, joined:'2005-12-07',age: 24}, {name:'nikki', orderTotal: 14.561, joined:'2001-11-02', age: 25}];
$scope.doSort = function(propName) {
$scope.sortBy = propName;
$scope.reverse = !scope.reverse;
};
};
angular.module('app').contoller('CustomersController', CustomersController)
}())
// app.controller('CustomersController', ['$scope', function($scope) {
// $scope.sortBy = 'name';
// $scope.reverse = false;
//
// $scope.customers = [{name:'sanjeet', joined:'2000-12-02', orderTotal: 10.096, age: 26}, {name:'gurpreet', orderTotal:201.961, joined:'2005-12-07',age: 24}, {name:'nikki', orderTotal: 14.561, joined:'2001-11-02', age: 25}];
//
// $scope.doSort = function(propName) {
// $scope.sortBy = propName;
// $scope.reverse = !scope.reverse;
// };
// }])
<!DOCTYPE html>
<html ng-app>
<head>
<title>My first AngularJS project</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h3>Customers</h3>
Filter: <input type="text" ng-model="customerFilter.name"/>
<br />
<table ng-controller="CustomersController">
<tr>
<th ng-click="doSort('name')">
Name
</th>
<th ng-click="doSort('age')">
Age
</th>
<th ng-click="doSort('joined')">
Joined
</th>
<th ng-click="doSort('orderTotal')">
Order Total
</th>
</tr>
<tr ng-repeat="customer in customers | filter: customerFilter | orderBy:sortBy:reverse" >
<td>
{{customer.name}}
</td>
<td>
{{customer.age}}
</td>
<td>
{{customer.joined | date: 'yyyy-MM-dd'}} <!--medium, longDate -->
</td>
<td>
{{customer.orderTotal | currency: 'y'}}
</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<script src="app/controllers/customersController.js"></script>
<script> var app = angular.module('app', [])</script>
</body>
</html>

You have multiple issues causing your app to not load. You should consider using angular.js rather than angular.min.js to receive better error messages in the console, which would help you to identify your errors.
You have a typo in your controller code. angular.module('app').contoller('CustomersController', CustomersController). .controller is missing an r.
You cannot use <html ng-app> in newer releases of angular (1.3+). This is a very old syntax. The correct syntax is to identify the app module. <html ng-app="app">.
Your App module must be defined before the controllers that use it. i.e.
<script> var app = angular.module('app', [])</script>
has to come before
<script src="app/controllers/customersController.js"></script>
Your Filter: <input type="text" ng-model="customerFilter.name"/> line is outside the controller, and thus won't function. You should move the ng-controller="CustomersController" to the body instead of the table, or a wrapping div.
I created a plunker and updated your code, showing the app in a functional status.

Related

Angular JS - dynamically add custom href link to value in table using ng-repeat based on a different value.

I am creating a table using ng-repeat that display some tickets info. Currently in the column "Ticket No" I am adding href link (when user click on the "Ticket No" it will open new tab and the URL will take the ticket no as parameter.
This a plunker I've created so it can show functionality as described above http://plnkr.co/edit/GB8WWz?p=preview
The problem I have now is that the href link might vary and it depends on the account column value. So if my "account = foo" set the href link of the Ticket No to "http://myfoopage.foo/ticketid...etc". If my "account = boo" set the href link for the Ticket No to "http://myboopage.boo/ticketid...etc".
Any idea on how to approach that ?
scriptang.js
angular.module('plunker', ['ui.bootstrap']);
function ListCtrl($scope, $dialog) {
$scope.items = [
{ticket: '123', description: 'foo desc',account:'foo'},
{ticket: '111', description: 'boo desc',account:'boo'},
{ticket: '222', description: 'eco desc',account:'eco'}
];
}
// the dialog is injected in the specified controller
function EditCtrl($scope, item, dialog){
$scope.item = item;
$scope.save = function() {
dialog.close($scope.item);
};
$scope.close = function(){
dialog.close(undefined);
};
}
index.html
<!doctype html>
<html ng-app="plunker">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="http://angular-ui.github.com/bootstrap/ui-bootstrap-tpls-0.1.0.js"></script>
<script src="scriptang.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="ListCtrl">
<table class="table table-bordered">
<thead>
<tr>
<th>Ticket No</th>
<th>Description</th>
<th>Account</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{item.ticket}}</td>
<td>{{item.description}}</td>
<td>{{item.account}}</td>
<td><button class="btn btn-primary" ng-click="edit(item)">Edit</button></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Updated plnkr here, I've made use of the ng-attr directive in combination with a function that creates an url.
$scope.getUrl = function (item) {
var url = '';
if(item.account === 'foo')
url = 'http://mywebpage.foo';
else
url = 'http://mwebpage.boo';
url += '/ticketid='+item.ticket
return url;
}

Issues accessing json data using AngularJS

I've just started learning angularJS and am trying to figure out why the following code doesn't work
<html>
<head>
<title>Angular JS Ajax</title>
</head>
<body>
<div ng-app="mainApp" ng-controller="studentController">
<table>
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Percentage</th>
</tr>
<tr ng-repeat="student in students">
<td>{{ student.Name }}</td>
<td>{{student.RollNo}}</td>
<td>{{student.Percentage}}</td>
</tr>
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script>
var mainApp = angular.module("mainApp");
mainApp.controller("studentController", function($scope,$http){
var url = "data.txt";
$http.get(url).success(function(response){
$scope.students = response;
});
});
</script>
</body>
</html>
When I change the attribute of ng-app to "" (instead of "mainApp"'), and replace the` code above with the following, the application works.
I'd really appreciate if anyone could explain to me why this is the case.
<script>
function studentController($scope, $http){
var url = "data.txt";
$http.get(url).success(function(response){
$scope.students = response;
});
};
</script>
Here's the data.txt file:
[
{
"Name": "Mahesh Parashar",
"RollNo": 101,
"Percentage": "80%"
},
{
"Name": "Dinkar Kad",
"RollNo": 191,
"Percentage": "75%"
}
]
Thank you!
You forgot to add [] with app module declaration
var mainApp = angular.module("mainApp",[]);
The first one is not working because you don't supply the right syntax for mainApp. You need to add [] for module declaration.
This should look like below:
var mainApp = angular.module('mainApp', []);
mainApp.controller('studentController', function($scope, $timeout) {
var url = "data.txt";
$http.get(url).success(function(response) {
$scope.students = response;
});
});
The second one is working fine simply because you don't have any app module declaration.
You need to Parse it to json object
Please try JSON.parse.
jsonObj = JSON.parse(response);
Hope this will help you

AngularJS ng-click not firing controller method

I'm sure everyone has seen questions of a similar ilk, and trust me when I say I have read all of them in trying to find an answer. But alas without success. So here goes.
With the below code, why can I not get an alert?
I have an ASP.Net MVC4 Web API application with AngularJS thrown in. I have pared down the code as much as I can.
I know that my AngularJS setup is working correctly because on loading my view it correctly gets (via a Web API call) and displays data from the database into a table (the GetAllRisks function). Given that the Edit button is within the controller, I shouldn't have any scope issues.
NB: the dir-paginate directive and controls are taken from Michael Bromley's excellent post here.
I would appreciate any thoughts as my day has degenerated into banging my head against my desk.
Thanks,
Ash
module.js
var app = angular.module("OpenBoxExtraModule", ["angularUtils.directives.dirPagination"]);
service.js
app.service('OpenBoxExtraService', function ($http) {
//Get All Risks
this.getAllRisks = function () {
return $http.get("/api/RiskApi");
}});
controller.js
app.controller("RiskController", function ($scope, OpenBoxExtraService) {
//On load
GetAllRisks();
function GetAllRisks() {
var promiseGet = OpenBoxExtraService.getAllRisks();
promiseGet.then(function (pl) { $scope.Risks = pl.data },
function (errorPl) {
$log.error("Some error in getting risks.", errorPl);
});
}
$scope.ash = function () {
alert("Bananarama!");}
});
Index.cshtml
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="OpenBoxExtraModule">
<head>
<title>Risks</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="~/Scripts/angular.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/Pagination/dirPagination.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/module.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/service.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/controller.js"></script>
</head>
<body>
<div ng-controller="RiskController">
<table>
<thead>
<tr>
<th>Risk ID</th>
<th>i3_n_omr</th>
<th>i3_n_2_uwdata_key</th>
<th>Risk Reference</th>
<th>Pure Facultative</th>
<th>Timestamp</th>
<th></th>
</tr>
</thead>
<tbody>
<tr dir-paginate="risk in Risks | itemsPerPage: 15">
<td><span>{{risk.RiskID}}</span></td>
<td><span>{{risk.i3_n_omr}}</span></td>
<td><span>{{risk.i3_n_2_uwdata_key}}</span></td>
<td><span>{{risk.RiskReference}}</span></td>
<td><span>{{risk.PureFacultative}}</span></td>
<td><span>{{risk.TimestampColumn}}</span></td>
<td><input type="button" id="Edit" value="Edit" ng-click="ash()"/></td>
</tr>
</tbody>
</table>
<div>
<div>
<dir-pagination-controls boundary-links="true" template-url="~/Scripts/AngularJS/Pagination/dirPagination.tpl.html"></dir-pagination-controls>
</div>
</div>
</div>
</body>
</html>
you cannot use ng-click attribute on input with angularjs : https://docs.angularjs.org/api/ng/directive/input.
use onFocus javascript event
<input type="text" onfocus="myFunction()">
or try to surround your input with div or span and add ng-click on it.
I've got the working demo of your app, code (one-pager) is enclosed below, but here is the outline:
removed everything concerning dirPagination directive, replaced by ngRepeat
removed $log and replaced by console.log
since I don't have a Web API endpoint, I just populated $scope.Risks with some items on a rejected promise
Try adjusting your solution to first two items (of course, you won't populate it with demo data on rejected promise)
<!doctype html>
<html lang="en" ng-app="OpenBoxExtraModule">
<head>
<meta charset="utf-8">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module("OpenBoxExtraModule", []);
app.service('OpenBoxExtraService', function ($http) {
//Get All Risks
this.getAllRisks = function () {
return $http.get("/api/RiskApi");
}
});
app.controller("RiskController", function ($scope, OpenBoxExtraService) {
//On load
GetAllRisks();
function GetAllRisks() {
var promiseGet = OpenBoxExtraService.getAllRisks();
promiseGet.then(function (pl) { $scope.Risks = pl.data },
function (errorPl) {
console.log("Some error in getting risks.", errorPl);
$scope.Risks = [{RiskID: "1", i3_n_omr: "a", i3_n_2_uwdata_key: "b", RiskReference: "c", PureFacultative:"d", TimestampColumn: "e"}, {RiskID: "2", i3_n_omr: "a", i3_n_2_uwdata_key: "b", RiskReference: "c", PureFacultative:"d", TimestampColumn: "e"}, {RiskID: "3", i3_n_omr: "a", i3_n_2_uwdata_key: "b", RiskReference: "c", PureFacultative:"d", TimestampColumn: "e"} ];
});
}
$scope.ash = function () {
alert("Bananarama!");}
});
</script>
</head>
<body>
<div ng-controller="RiskController">
<table>
<thead>
<tr>
<th>Risk ID</th>
<th>i3_n_omr</th>
<th>i3_n_2_uwdata_key</th>
<th>Risk Reference</th>
<th>Pure Facultative</th>
<th>Timestamp</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="risk in Risks">
<td><span>{{risk.RiskID}}</span></td>
<td><span>{{risk.i3_n_omr}}</span></td>
<td><span>{{risk.i3_n_2_uwdata_key}}</span></td>
<td><span>{{risk.RiskReference}}</span></td>
<td><span>{{risk.PureFacultative}}</span></td>
<td><span>{{risk.TimestampColumn}}</span></td>
<td><input type="button" id="Edit" value="Edit" ng-click="ash()"/></td>
</tr>
</tbody>
</table>
<div>
<div></div>
</div>
</div>
</body>
</html>
Thank you all for your help, particularly #FrailWords and #Dalibar. Unbelievably, this was an issue of caching old versions of the javascript files. Doh!
You can't directly use then on your service without resolving a promise inside it.
fiddle with fallback data
this.getAllRisks = function () {
var d = $q.defer();
$http.get('/api/RiskApi').then(function (data) {
d.resolve(data);
}, function (err) {
d.reject('no_data');
});
return d.promise;
}
This will also fix your problem with getting alert to work.

bootstrap-table not rendering upon updating model in Angular

Hi I am not able to render table using bootstrap-table and angular. here is my code, I think I need to call bootstrap-table init method in angular ajax call. Can some one guide me on how to do this..?
angular
.module('reports')
.controller(
'ReportCtrl',
[
'$scope',
'$http',
'ngProgress',
function($scope, $http, ngProgress) {
var vm = this;
vm.mdp = {};
vm.mdp.data = [];
vm.mdp.columns = [];
$scope.submit = function() {
var report = $scope.tab;
$http.post('/reports/cmd/getData', {
report : report,
date : createdAfter
}).success(function(data) {
vm.mdp.data = data;
$.each(data[0], function(key, value){
vm.mdp.columns.push(key);
});
}).error(function(error) {
alert(error);
});
};
} ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mdp" class="panel" ng-controller="ReportCtrl as report" ng-show="panel.isSelected('mdp')">
<table data-toggle="table" data-show-columns="true" data-search="true" data-show-export="true" data-pagination="true" data-height="299">
<thead>
<tr>
<th ng-repeat="c in report.mdp.columns" data-field= {{c}} >{{ c }}</th>
</tr>
</thead>
<tr ng-repeat="r in report.mdp.data">
<td ng-repeat="c in report.mdp.columns">{{ r[c] }}</td>
</tr>
</table>
</div>
Integrating Bootstrap Table with Angular is solved here:
https://github.com/wenzhixin/bootstrap-table/issues/165
https://github.com/AkramKamal/bootstrap-table-examples/tree/master/integrate
I have some minor changes in my implementation of this solution which I will upload to Github / JSFiddle shortly. But the links above will allow you to get going.

AngularJS - Error: [ng:areq] Argument 'CustomersController' is not a function, got undefined

Here is my view index.html:
<!DOCTYPE html>
<html ng-app>
<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</th>
<th ng-click="doSort('joined')" >Joined</th>
</tr>
<tr ng-repeat="cust in customers | filter:customerFilter | orderBy:sortBy:reverse">
<td>{{ cust.name | uppercase }}</td>
<td>{{ cust.city | lowercase }}</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/controllers/customersController.js"></script>
</body>
</html>
And here is my controller:
function CustomersController($scope) {
$scope.sortBy = 'name';
$scope.reverse = false;
$scope.customers = [{
joined: '2012-12-02',
name: 'Dylan',
city: 'Buffalo',
orderTotal: 9.521
}, {
joined: '1932-12-02',
name: 'Pete',
city: 'Detroit',
orderTotal: 111.521
}, {
joined: '1967-11-04',
name: 'Sampress',
city: 'Kanas City',
orderTotal: 92.521
}];
$scope.doSort = function(propName) {
$scope.sortBy = propName;
$scope.reverse = !$scope.reverse;
};
}
When I open my index.html file in the browser, I continue to get
Error: [ng:areq] Argument 'CustomersController' is not a function, got undefined
All of my files are in the right place, I even tried added it as a plain script tag and still am getting the same error, not sure what I'm doing wrong here.
You are probably either not defining your controller in the global namespace or not defining your controller early enough.
Check to see if you're defining the controller in the global namespace by looking at window.CustomersController. window.CustomersControllershould be your controller function. If you're not defining your controller in the global namespace try adding:
window.CustomersController = CustomersController;
If you're not defining your controller early enough make sure that you're not defining your controller after load events, after DOM ready events, etc. Notice this JS Fiddle only works when "no wrap in - " or "no wrap in - " is selected. It does not work if "onload" or "onDOMready" are selected.
Alternatively, you can name your app:
<html ng-app="foo">
</html>
angular.module("foo", [])
.controller("CustomersController", function CustomersController() {});
Try this
<html ng-app="App">
Controller
myApp = angular.module('App',[]);
myApp.controller('CustomersController',['$scope',function($scope) {
//Your code here
}]);

Resources