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

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>

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>

Having a formular call a controller in AngularJS

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

how to get the unique id of array element on click through angularjs from firebase database

HTML:
<div ng-controller="getIdController">
<div class="container">
<div class="row">
<div class="col-md-6">
<hr />
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in userData">
<td> {{ user.name }} </td>
<td> {{ user.age }} </td>
<td> {{ user.gender }} </td>
<td><button class="btn btn-warning" ng-click="getObjectId()">Get Id</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
App Js:
var crudApp = angular.module('crudApp', ['firebase']);
crudApp.controller('getIdController', ['$scope', '$firebaseArray', function($scope, $firebaseArray){
var ref = new Firebase('https://blistering-fire-4719.firebaseio.com/users');
$scope.userData = $firebaseArray(ref);
$scope.getObjectId = function(){
$scope.userData.$loaded()
.then(function(id){
var obj = id;
console.log(obj);
});
}
}]);
Explanation:
Ok here In firebase i have User table and it has 3 objects each with unique id. Currently I am trying to extract the unique id for object on click of Get Id button in html. But the problem is if I do console.log(id) the function getObjectId() gives me //Array [ Object, Object, Object ].. clicking on object takes me to its data and it has $id as -K9jyc0K9i28h53d23Uw..
Is there any way to get the unique id for a particular element on clicking the button
I want this unique id to be shown for element on clicking a particular element/object in html.
Please help.
If your user object has the id property on it, you can just refer directly to that. You can pass it as a parameter from your ng-click directive:
<button ng-click="selectUser(user)">
and in your controller:
$scope.selectUser = function(user) {
console.log(user); // should emit the user object. is id a property?
}
If all of your objects use the same property, you can have a single function:
$scope.showObjectId = function(object) {
alert(object.id);
}
You can show the id in the html like this (within the ng-repeat):
<td> {{ user.$id }} </td>
Or send it to the ng-click function (within the ng-repeat):
<button class="btn btn-warning" ng-click="getObjectId(user.$id)">Get Id</button> //Just send the id to the function
<button class="btn btn-warning" ng-click="getObjectId(user)">Get Id</button> //Send the etire user object to the function
And in you javascript you can use it like this:
$scope.getObjectId = function(user){
//If you only send the id to this function you can get the entire user object like this (it gives a $firebaseObject i think):
var user = $scope.userData.$getRecord(user);
//Here you can do anything with the user
//Update user data
$scope.UserData.$save(user);
//Remove user
$scope.UserData.$remove(user);
}

Get data from row when clicked and display to editable dialog box

I'm trying to use Angularjs to get data from a row in a table when it is clicked and display it in an editable dialog box. How can I do this? Here's what I have so far:
<table>
<thead>
<tr>
<th>ID No.</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Gender</th>
<th>Time</th>
<th>Date</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="walkin_member in data | filter:searchFilter">
<td><a class="click">{{walkin_member.id}}</a></td>
<td>{{walkin_member.firstname}}</td>
<td>{{walkin_member.lastname}}</td>
<td>{{walkin_member.gender}}</td>
<td>{{walkin_member.time}}</td>
<td>{{walkin_member.datestamp}}</td>
<td>{{walkin_member.type}}</td>
</tr>
</tbody>
</table>
This is my dialog box markup:
<div id="dlgbox">
<div id="dlg-header">Information</div>
<div id="dlg-body">
Firstname <input type="text" value="{{walkin_member.firstname}}"><br/>
Lastname <input type="text" value="{{walkin_member.lastname}}"><br/>
Gender <input type="text" value="{{walkin_member.gender}}"><br/>
Type <input type="text" value="{{walkin_member.type}}"><br/>
</div>
<div id="dlg-footer">
<button onclick="dlgUpdate()">Update</button>
<button onclick="dlgExit()">Exit</button>
</div>
</div>
Here's my controller:
myApp.controller('loglistController', ['$scope', '$http', function ($scope, $http) {
$http.get("../php/loglistajax.php")
.success(function(data){
$scope.data = data;
})
.error(function() {
$scope.data = "error in fetching data";
});
}]);
the dialog box is hidden, it will just show if the function is triggerd onclick
here's my javascript.
function showDialog(){
var whitebg = document.getElementById("white-background");
var dlg = document.getElementById("dlgbox");
whitebg.style.display = "block";
dlg.style.display = "block";
var winWidth = window.innerWidth;
dlg.style.left = (winWidth/2) - 480/2 + "px";
dlg.style.top = "150px";
}
Add an ng-click event to the anchor tag in each row and pass the current member to the method.
<tr ng-repeat="walkin_member in data | filter:searchFilter">
<td>
<a class="click" href="#"
ng-click="showInEdit(walkin_member)">{{walkin_member.id}}</a>
</td>
</tr>
Now in your controller, Add a new property to hold the selected member and a method called showInEdit()
myApp.controller('loglistController', ['$scope', '$http', function ($scope, $http) {
$scope.data=[];
$scope.selectedMember={ firstname:"",lastname:"",gender:"",type:"" }; //new property
$http.get("../php/loglistajax.php")
.success(function(data){
$scope.data = data;
})
.error(function() {
$scope.data = "error in fetching data";
});
$scope.showInEdit=function(member){
$scope.selectedMember = member;
};
}]);
And in your model dialog, you will use the selectedMember property.
<div id="dlgbox">
<div id="dlg-header">Information</div>
<div id="dlg-body">
Firstname <input type="text" ng-model="selectedMember.firstname" />
</div>
</div>

Angular.js ng-click event not firing

I'm new to Angular JS, and I'm trying to implement a page to display, add, edit and delete objects from a REST API. I have functions to add, edit and delete items bound to ng-click, but the edit and delete events are not firing. The only difference between the add and edit/delete bindings seems to be that the edit/delete ng-clicks are inside an ng-repeat.
JavaScript code:
process_errors = function(rejection) {
// Error processing code
}
var exampleApp = angular.module('exampleApp', ['ngResource']);
exampleApp.factory('Example', ['$resource', function($resource) {
return $resource('/api/v1/example/:example_id', {example_id:'#id'});
}]);
exampleApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common['X-CSRFToken'] = $.cookie('csrftoken');
}]);
exampleApp.controller('exampleListCtrl', ['$scope', 'Example',
function($scope, Example) {
$scope.examples = Example.query();
$scope.newExample = new Example();
$scope.add = function() {
$scope.newExample.$save().then(function(result){
$scope.examples.push(result);
}).then(function() {
$scope.newExample = new Example();
}, process_errors);
}
$scope.editExample = function(example) {
console.log('editing');
var idx = $scope.examples.indexOf(example);
$scope.examples[idx].$save().then(function(result) {
}, function(rejection) {
process_errors(rejection);
$scope.editMode = true;
});
}
$scope.deleteExample = function(example) {
console.log('deletion');
example.$delete().then(function(){
var idx = $scope.examples.indexOf(example);
$scope.examples.splice(idx, 1);
});
}
}]);
HTML:
<div id="content-container" ng-app="exampleApp">
<table class="table table-striped" ng-controller="exampleListCtrl">
<thead>
<!-- Table headers -->
</thead>
<tbody>
<tr>
<form class="form-inline" role="form">
<td><input type="text" class="form-control" ng-model="newExample.start_date" placeholder="2013-11-25"></input></td>
<!-- more fields in the same format -->
<td><button class="btn btn-primary" ng-click="add()">Add</button></td>
</form>
</tr>
</tbody>
<tbody>
<tr ng-repeat="example in examples">
<form class="form-inline" role="form">
<td>
<span ng-hide="editMode">{{example.start_date}}</span>
<input ng-show="editMode" type="text" class="form-control" ng-model="example.start_date" value="{{example.start_date}}"></input>
</td>
<!-- more fields in the same format -->
<td>
<button ng-hide='editMode' class="btn btn-default" ng-click="editMode = true;">Edit</button>
<button ng-show='editMode' class="btn btn-primary" ng-click="editExample(example); editMode = false">Save</button>
</td>
<td><button class="btn btn-danger" ng-click="deleteExample(example)"><span class="glyphicon glyphicon-remove"></span></td>
</form>
</tr>
<tbody>
</table>
</div>
I've also tried binding the functions to $parent.editExample(example).

Categories

Resources