I am new to AngularJS and I am looking for advice on refreshing a module's table contents (which is a list of names and post codes in this case).
Here in script I reference the json file I want to refresh on a button press:
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http, $timeout) {
$http.get("jsondisplay4.php")
.then(function (response) {$scope.names = response.data;});
});
</script>
And here is the HTML:
<div ng-app="myApp" ng-controller="customersCtrl">
<button ng-click="doRefresh()">Refresh</button>
<table>
<tr>
<td>Ref</td>
<td>Company</td>
<td> </td>
</tr>
<tr ng-repeat="x in names">
<td>{{ x.Ref }}</td>
<td>{{ x.CompanyName }}</td>
<td>
<input type="text" name="textfield" id="textfield" ng-model="x.PostCode"></td>
</tr>
</table>
</div>
I currently have "doRefresh()" as the potential name, its just where to place the correct code and what it should be.
Any help is greatly appreciated.
app.controller('customersCtrl', function($scope, $http, $timeout) {
function run(){
$http.get("jsondisplay4.php")
.then(function (response) {
$scope.names = response.data;
});
}
$scope.doRefresh = function(){
run();
}
run();
});
When controller is loaded, it will call run method. $scope.doRefresh will do the same
Related
I am making my first AngularJS App followed by this tutorial:
https://www.toptal.com/angular-js/a-step-by-step-guide-to-your-first-angularjs-app
The problem is in my App when I direct to view 1, it works fine. It can load the HTML file with the information of all the drivers. However, when I click one specific driver, it can't load the HTML page for the particular driver. How can I redirect to the HTML page of the particular driver?
The App structure is
view 1:
view1.html
js
driver
---------driver.html
view 2
view2.html
<p>This is the partial for view 1.</p>
<input type="text" ng-model="filterTxn.Driver.givenName" placeholder="Search..."/>
<table>
<thead>
<tr><th colspan="4">Drivers Championship Standings</th></tr>
</thead>
<tbody>
<tr ng-repeat="driver in driversList | filter: filterTxn ">
<td>{{$index + 1}}</td>
<td>
<a href="#/view1/driver/{{driver.Driver.driverId}}">
{{driver.Driver.givenName}} {{driver.Driver.familyName}}
</a>
</td>
<td>{{driver.Constructors[0].name}}</td>
<td>{{driver.points}}</td>
</tr>
</tbody>
</table>
<p>detail page for a specific driver</p>
<section id="main">
<- Back to drivers list
<nav id="secondary" class="main-nav">
<div class="driver-picture">
<div class="avatar">
<img ng-show="driver" src="img/drivers/{{driver.Driver.driverId}}.png" />
<img ng-show="driver" src="img/flags/{{driver.Driver.nationality}}.png" /><br/>
{{driver.Driver.givenName}} {{driver.Driver.familyName}}
</div>
</div>
<div class="driver-status">
Country: {{driver.Driver.nationality}} <br/>
Team: {{driver.Constructors[0].name}}<br/>
Birth: {{driver.Driver.dateOfBirth}}<br/>
Biography
</div>
</nav>
<div class="main-content">
<table class="result-table">
<thead>
<tr><th colspan="5">Formula 1 2013 Results</th></tr>
</thead>
<tbody>
<tr>
<td>Round</td> <td>Grand Prix</td> <td>Team</td> <td>Grid</td> <td>Race</td>
</tr>
<tr ng-repeat="race in races">
<td>{{race.round}}</td>
<td><img src="img/flags/{{race.Circuit.Location.country}}.png" />{{race.raceName}}</td>
<td>{{race.Results[0].Constructor.name}}</td>
<td>{{race.Results[0].grid}}</td>
<td>{{race.Results[0].position}}</td>
</tr>
</tbody>
</table>
</div>
</section>
view1.js:
'use strict';
angular.module('myApp.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', [function() {
}]);
angular.module('F1FeederApp', [
'F1FeederApp.services',
'F1FeederApp.controllers',
'ngRoute'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when("/drivers/:id", {templateUrl: "view1/driver/driver.html", controller: "driverController"}).
otherwise({redirectTo: '/view1'});
}]);
services.js:
angular.module('F1FeederApp.services', [])
.factory('ergastAPIservice', function($http) {
var ergastAPI = {};
ergastAPI.getDrivers = function() {
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/2013/driverStandings.json?callback=JSON_CALLBACK'
});
}
ergastAPI.getDriverDetails = function(id) {
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/2013/drivers/'+ id +'/driverStandings.json?callback=JSON_CALLBACK'
});
}
ergastAPI.getDriverRaces = function(id) {
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/2013/drivers/'+ id +'/results.json?callback=JSON_CALLBACK'
});
}
return ergastAPI;
});
angular.module('F1FeederApp.controllers', []).
/* Drivers controller */
controller('driversController', function($scope, ergastAPIservice) {
$scope.nameFilter = null;
$scope.driversList = [];
$scope.searchFilter = function (driver) {
var re = new RegExp($scope.nameFilter, 'i');
return !$scope.nameFilter || re.test(driver.Driver.givenName) || re.test(driver.Driver.familyName);
};
ergastAPIservice.getDrivers().success(function (response) {
//Digging into the response to get the relevant data
$scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings;
});
}).
/* Driver controller */
controller('driverController', function($scope, $routeParams, ergastAPIservice) {
$scope.id = $routeParams.id;
$scope.races = [];
$scope.driver = null;
ergastAPIservice.getDriverDetails($scope.id).success(function (response) {
$scope.driver = response.MRData.StandingsTable.StandingsLists[0].DriverStandings[0];
});
ergastAPIservice.getDriverRaces($scope.id).success(function (response) {
$scope.races = response.MRData.RaceTable.Races;
});
});
Use ui-sref instead of href to trigger the state change.
<p>This is the partial for view 1.</p>
<input type="text" ng-model="filterTxn.Driver.givenName" placeholder="Search..."/>
<table>
<thead>
<tr><th colspan="4">Drivers Championship Standings</th></tr>
</thead>
<tbody>
<tr ng-repeat="driver in driversList | filter: filterTxn ">
<td>{{$index + 1}}</td>
<td>
<a ui-sref="/driver/{{driver.Driver.driverId}}">
{{driver.Driver.givenName}} {{driver.Driver.familyName}}
</a>
</td>
<td>{{driver.Constructors[0].name}}</td>
<td>{{driver.points}}</td>
</tr>
</tbody>
</table>
I have an $ngController that is being used in two views. The first view has an <table> with ng-repeat that lists all my data from the db.
I get the selected object form the table by using get($index) and set it to a $scope variable.
The problem is that when i cannot use this same $scope variable on the other view, because its value is undefined. Both views share the same ng-controller.
My Question is: is the redirection cleaning my $scope? Is there any way i can share this data between pages since my application isn't single page?
Things i tried:
1 - Share data through a factory
2 - Using $rootScope
First View - Table with ng-repeat
<table class="table table-striped">
<thead>
<tr>
<th>CNPJ</th>
<th>Razão Social</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="company in companies | filter:{companyName:searchString}">
<td> {{ company.cnpj }}</td>
<td> {{ company.companyName }}</td>
<td>
Visualizar
<button type="button" class="btn btn-warning btn-xs">Editar</button>
<button type="button" class="btn btn-danger btn-xs">Deletar</button>
</td>
</tr>
</tbody>
</table>
Controller
angular.module("distCad").controller("adminCtlr", function($scope, $http, config, $window, $cacheFactory){
$scope.searchTerm = null;
$scope.hideSearcAlert = true;
$scope.companies = [];
$scope.cache = $cacheFactory('companyCache');
$scope.expireLogin = function(){
localStorage.removeItem("type");
$window.location.href = "/";
}
$scope.getResults = function(){
$scope.searchTerm = true;
$http.get("/api/companies").then(
function successCallback(response){
$scope.companies = response.data;
},
function errorCallback(response){
console.log("aaaa" + response);
}
);
}
$scope.getCompany = function(){
return $scope.cache.get("company");
}
$scope.setCompanyFromTable = function(index){
$scope.cache.put("company", $scope.companies[index]);
}
});
Destination View - Part where i am testing
<div class="container" ng-init="getCompany()">
<div class="row">
<div class="col-md-12">
<h2>Dados da empresa {{cache.get("company").companyName}}</h2>
I'm having a little issue with learning AngularJS. I'm not 100% sure what are controller about. For exemple, i have the following html div which simply display the result of a SQL request :
<div ng-app="searchApp" ng-controller="searchCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x }}</td>
</tr>
</table>
</div>
And here's the controller :
<script>
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function($scope, $http)
{
$http.get("server.php")
.then(function (response)
{
$scope.result = response.data;
})
.then(function(response){
console.log(response);
})
});
</script>
server.php is returning a simple array of strings, so the page display immediatly a list of names. I would like to add a button on this page, and display this list only AFTER the button has been clicked. I tried to add a form :
<div ng-app="searchApp" ng-controller="searchCtrl">
<form class="well form-search">
<button type="submit" class="btn" ng-click="search()">Search</button>
</form>
<table>
<tr ng-repeat="x in result">
<td>{{ x }}</td>
</tr>
</table>
</div>
but this form is calling the search() function, which doesn't exist right now. I would like to call the controller instead.
I don't know if i have made myself very clear, sorry.
//template (no form tag needed)
<button type="button" class="btn" ng-click="search()">Search</button>
//controller
$scope.search = function(){
$http.get("server.php")
.then(function (response)
{
$scope.result = response.data;
})
.then(function(response){
console.log(response);
})
}
In the following code, I am trying to pass the table cell (as a DOM object) to the function, but this doesn't mean the DOM object for the table cell, it appears that it refers to the $scope. Any idea how to do this?
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr >
<td ng-click="dum();">ONE</td>
<td>TWO</td>
</tr>
<tr ng-repeat="x in names">
<td ng-click="dum(this);">{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
obj1 = "haha";
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function (response) {$scope.names = response.records;});
$scope.dum = function(x) { obj1 = x; console.log(x); }
});
</script>
</body>
</html>
In angular, you should always code against your data. Coding against the DOM is unnecessary in all but the most extreme edge cases, and when it is necessary, it's usually best done in a directive, where you can control how the rest of the angular app is updated.
In your case, you don't need to access the DOM, or the element, or even an event. You already have all the information you need in order to handle your code with the data.
<tr ng-repeat="x in names">
<td ng-click="dum(x);">{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
and in the controller:
$scope.dum = function(x) { console.log(x); }
You could, probably, do this:
In your HTML
<td ng-click="dum($event);">{{ x.Name }}</td>
In your Javascript
$scope.dum = function(e) { obj1 = e.target; console.log(x); }
//e.target will be the clicked element.
I would not recommend accessing the DOM from a controller, but you can use the $event.target. Here's a plunker example: http://plnkr.co/edit/wFdnPJVa7BHOcvkPqNNT?p=preview
angular.module('Test', [])
.controller('testCtrl', ['$scope', function($scope)
{
$scope.myFunc = function(e)
{
console.dir(e.target);
}
}]);
And the HTML
<body ng-app="Test">
<div ng-controller="testCtrl">
<button ng-click="myFunc($event)">Click Me</button>
</div>
</body>
I'm using angularjs. What i want to do is when user click button , angularjs will checking item id in database. If item id exist in database, #modal will be showed instead of alert like this question. Is it possible to do this with angularjs? If possible how..
HTML
<div id="container" ng-app='two_way' ng-controller="aa" >
<div align="center">
<h1 align="center"> Nutrition Scheduling List </h1>
<button ng-click="loadsched()" >LOAD SCHEDULE</button>
</div>
<span ng-hide="load==null">
<table border='1' bgcolor="CCFFFF" align="center">
<tr ><td><b>Item Name</b></td><td><b>Scheduled Time</b></td><td><b>Run Time</b></td><td><b>Create Time</b></td><td><b>Status</b></td><td><b>Response</b></td></tr>
<tr ng-repeat="data in load | orderBy: 'searchitem'">
<td>
{{data.searchitem}}
</td>
<td>
{{data.Scheduledtime}}
</td>
<td>
{{data.runt}}
</td>
<td>
{{data.CurrentTime}}
</td>
<td>
{{data.STATUS}}
</td>
<td>
<input type="button" class="btn btn-lg btn-primary" value="RESPONSE" onclick="window.open('http://localhost:3000/search/{{data._id}}','popUpWindow','height=500,width=400,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');">
</td>
</tr>
</table>
</span>
<script src="more.js"></script>
</div>
Controller more.js
var app=angular.module('two_way', ['ui.bootstrap']);
app.controller('aa',function($scope,$http){
$scope.loadsched=function(){
$http.post("http://localhost:3000/a").success(function(data){
//console.log(data);
$scope.load=angular.fromJson(data);
}).error(function(){alert("Error");});
}
});
Very simple :-
1) Apply $modal to your main controller.
2) Use $modal.open() to open modal anywhere and it will return a promise.
$modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size
);
Here template is file or Id of your modal template.
size:sm,lg
Controller it is the controller of your modal.
For example:-
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
$modalInstance service is used to close and return the promise from modal.
$modalInstance.close($scope.selected.item); close the modal and return data to controller.
$modalInstance.dismiss('cancel'); it is simply dismiss the controller.
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
Here modalInstance.result is used to get data from modal controller to your main controller.
Official Plunker