Having a formular call a controller in AngularJS - javascript

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);
})
}

Related

get value from json to angularjs object

I want to get value from this JSON response into angular js object.
[{"label":"Test","value":""," Test2":"","required":"mandatory","type":"text","typeemail":""}]
into angularjs object, here is .html
<tr ng-repeat="item in searched = (coba | filter:customerid | filter:search ) | coba:(currentPage-1)*itemsPerPage |limitTo:viewby ">
<td>
<p>{{item.additionaldata_pay}}</p>
</td>
</tr>
here is .js file
app.controller("cobacont", ['$scope','$http',function($scope,$http) {
$scope.cari = function () {
$http.get('...a='+$scope.month).then(function(response){
$scope.coba = response.data;
});
}
}]);
var app = angular.module('main-App', []);
app.controller('customersCtrl', function($scope,$http) {
$scope.records = [];
$http.get("https://...a='+$scope.month")
.then(function (response) {
console.log(response.data);
$scope.records = response.data;
});
});
here is my html table
<tr dir-paginate="value in data | itemsPerPage:5" total-items="totalItems" ng-repeat="user in records">
<td>{{$index+1}}</td>
<td >{{user.label}}</td>
<td >{{user.value}}</td>
<td>{{user.required}}</td>
<td>
<button data-toggle="modal" data-target="#edit-data" class="btn btn-primary" ng-click="selectedUser(user)">Edit</button>
<button ng-click="DeleteUser(user)" class="btn btn-danger" data-toggle="modal" data-target="#delete-data">Delete</button>
</td>
</tr>
It's best that you put all data processing in your controller. And leaving the HTML to display your data only.
So, in your controller, add another method that will do your search, filter, and pagination, and the result can then be used in your view.
$scope.getData = function () {
var data = $filter('filter')($scope.coba, $scope.searchQuery);
// do pagination here...
return data;
}
Your HTML can then become something like this:
<tr ng-repeat="item in getData()">
<td>
<p ng-bind="item.additionaldata_pay"></p>
</td>
</tr>

angularjs: refresh a module

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

Angular.js - Redirection is cleaning my $scope(?)

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>

pass dom object to processing function in angularjs

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>

how to use modal pop up in angularjs-ui bootstrap

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

Categories

Resources