passing data to another page angular js - angularjs

I am new to Angular js and want to pass the data from a submit to another page.
How can I make this in angularjs?
I can add lists to a single customer, but I can display the data only in the same page.
I want to display the data in another page after the submit.
I have learnd today, how to use the services, but still I can not pass data from a page to another.
Can anyone help me with a example?
Sorry for my bad English and thank you
// ngRoute code
var app = angular.module('appCheck', ['ngRoute', 'angularUtils.directives.dirPagination']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
controller : "customersCTRL",
templateUrl : "/app/customers/customers.html"
})
.when("/customers", {
controller : "customersCTRL",
templateUrl : "/app/customers/customers.html"
})
.when("/lists", {
controller : "listsCTRL",
templateUrl : "/app/lists/lists.html"
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
}]);
// controller code
$scope.getList = function(id) {
listsService.getSingleCustomer(id)
.then(function successCallback(response, data) {
//$scope.clearForm();
$scope.customer = response.data[0].name;
$scope.id_customer = response.data[0].id;
//$scope.getAll();
//console.log(id);
})
}
$scope.createList = function createList() {
listsService.createList()
.then(function successCallback(response, data) {
$('#addLists').modal('hide');
$scope.clearForm();
})
};
// services code
this.createLists = function() {
return $http.post('/lists/add' , {
"name" : $scope.name,
"id_customer" : $scope.id_customer
})
}
<button ng-click="getListExample(x.id)" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addL"><span class="glyphicon glyphicon-plus" aria-hidden="true"> Add List</span></button>
<h4 class="modal-title">Add Liste for the customer <span contenteditable="false" ng-bind="cust"></span></h4>
<label>Name of the List</label>
<input type="text" ng-model="name">
<button type="button" ng-click="createListExample()" class="btn btn-primary">Create</button>

You shouldn't pass data. Instead, the other page should get the data it needs to show, from the backend, based on the path parameters.
So the path for the list of customers should be /customers. The associated component gets the list of customers from the backend.
Then, to display a single customer, you would go to /customers/:customerId (example: /customers/42). The componenty would get the details of the customer 42 from the backend.
To display the lists of the customer 42, for example after you have added a list to that customer, you would go to /customers/:customerId/lists (example: /customers/42/lists). The component would get the lists of the customer 42 from the backend.

Related

angular 1 - routing and api

Trying to write a simple SPA. Using MEAN.
API through node are all working.
Have set up routes in my main controller
// create the module and name it
var boardingApp = angular.module('boardingApp', ['ngRoute']);
boardingApp.config(function($routeProvider) {
$routeProvider
// route for the home page that lists all tenants
.when('/', {
templateUrl : 'js/templates/tenants.html',
controller : 'tenantsController'
})
// route for a specifc tenant
.when('/tenant/:id', {
templateUrl : 'js/templates/tenant.html',
controller : 'tenantController'
})
});
boardingApp.controller('tenantsController', ['$scope','$http','$log', function($scope, $http,$log) {
$http.get(URL + "/api/tenants")
.then(function(response){ $scope.details = response.data; });
}]);
boardingApp.controller('tenantController', ['$scope','$http','$location','$log', function($scope, $http, $location, $log) {
if ( $location.search().hasOwnProperty( 'id' ) ) {
var myid = $location.search()['id'];
console.log(myid)
myURL = URL + "/api/tenants/"+myid
console.log(myURL)
$http.get(myURL)
.then(function(response){ $scope.tenant = response.data; });
console.log($scope.tenant)
}
}]);
boardingApp.controller('readmeController', function($scope, $http) {
$scope.message = "This is the message"
});
the root route work finds calls the API generates a table. All good
then main part of that template is this
<tbody id="tenantsTable">
<tr ng:repeat = "tenant in details | filter : true: tenant.activeTenant ">
<td><a ng-href = "#/tenant.html?id={{tenant._id}}" >View</td>
<td>{{tenant.roomNumber}} </td>
<td>{{tenant.firstName}} </td>
<td>{{tenant.lastName}} </td>
<td>{{tenant.paymentFrequency}} </td>
<td>${{tenant.rentAmount}} </td>
<td> {{tenant.leaseEnd | date: 'dd MMM yyyy'}} </td>
</tr>
</tbody>
I want to click on the "View" link and pull data from DB for each tenant through and API call that just needs the Tenant id - standard stuff.
My controller is not picking up the request and when i click on the link on the Tennants page it just ends up blank.
what am i missing here? the api call s are all good and working fine
You anchor tab is incorrect, it should be in correct pattern like "#/tenant/{{tenant._id}}"
ng-href="#/tenant/{{tenant._id}}"
Additionally you should retrieve a route parameter inside tenantController by using $routeParams.id API instead of $location.search() which would be look for query parameter.

Search Toolbar with AngularJS

This is a newbie question about Angular 1.4.
My Main Question
I have the following search view:
'use strict';
var module = angular.module('myapp.search', ['ngRoute', 'ngResource']);
module.config(function ($routeProvider) {
$routeProvider.when('/search', {
templateUrl: 'search/search.html',
controller: 'SearchCtrl'
});
});
module.factory('Search', function ($resource) {
return $resource('http://www.myapp.com/api/search', {}, {
query: {
method: 'GET',
params: {},
isArray: false
}
});
});
module.controller('SearchCtrl', function ($scope, Search) {
$scope.results = [];
$scope.query = '';
$scope.doSearch = function (query) {
Search.query({q: query}).$promise.then(function (result) {
$scope.results = result.results;
});
};
});
And the partial HTML (search.html):
#search.html
<input placeholder="search" ng-model="query" />
<button ng-click="doSearch(query)" />
<h1>Results</h1>
<ol>
<li ng-repeat="result in results">{{ result }}</li>
</ol>
...
This works perfectly, the problem is when I want to put the search input in a toolbar (defined in index.html):
#index.html
<div ng-controller="SearchCtrl">
<div class="toolbar">
<input placeholder="search" ng-model="query" />
<button ng-click="doSearch(query)">
</div>
...
In this case, by pushing the search button the query is executed in the back-end but the results are not updated in $scope. what's wrong? I've tried calling $scope.$apply() with no luck. I'm lost with this.
Bonus Question
Given that the search functionality is in the toolbar (always visible) users can execute queries in any place of the website. How can I redirect the response to http://www.myapp.com/search?
Thanks in advance.
You have two distinct instances of SearchCtrl, each with its own distinct scope: one in the navbar (dur to ng-controller="SearchCtrl"), and one in the main view (due to controller: 'SearchCtrl').
So the search in the navbar modifies the scope of the navbar controller, and the scope of the main view doesn't know anything about it.
If you want to got to the search main view when something is searched in the navbar, simply use
$location.url('/search?query=' + theEncodedQueryTypedByTheUser);
And in the search route's resolve function, or in its controller, get the route param named query, send the HTTP request, and update the scope with the results.

Pushing data from Angular Bootstrap Typeahead into another tab using UI-Router

I have 3 tabs: customers, billing, and method. On the first tab I have the Bootstrap Typeahead, that is connected to a json file of customers. The second tab is a detailed view of the customer account with outstanding charges. Finally, the third tab is to actually charge the customer with a credit card. Additionally, I am using UI Router to navigate through a complex hierarchy. the tabs are named views of a page called make-payments, which is a child of a parent state called payments. I am trying to use the typeahead in the first tab (customers) to select and view a customer detail in the second tab (billing). I am hoping this happens when the user selects the person from the dropdown, they should immediately navigate to the next tab, and the next tab should show that persons details. I am having some difficulty really understanding how to get the data from the typeahead to the next two tabs, and if I need a service to do this or not.
make-payment.html(My tabs):
<h3 class="text-center">Make a One-Time Payment</h3>
<uib-tabset type="pills nav-pills-centered">
<uib-tab heading="1">
<div ui-view=customers></div>
</uib-tab>
<uib-tab heading="2">
<div ui-view=billing></div>
</uib-tab>
<uib-tab heading="3">
<div ui-view=method></div>
</uib-tab>
</uib-tabset>
customers.html & the typeahead.js ctrl:
angular
.module('myApp')
.controller('TypeAheadCtrl', function($scope, $http) {
$http.get('customers.json').success(function(data) {
$scope.customers = data;
});
var self = this;
self.submit1 = function() {
console.log('First form submit with', self.customer)
};
});
<div ng-controller="TypeAheadCtrl as ctrl">
<form ng-submit="ctrl.submit1()" name="customerForm">
<div class="form-group">
<label for="account">Account Number</label>
<input type="text" class="form-control" placeholder="Search or enter an account number" ng-model="ctrl.customer.account" uib-typeahead="customer as customer.index for customer in customers | filter:$viewValue | limitTo:6" typeahead-template-url="templates/customer-tpl.html"
typeahead-no-results="noResults">
</div>
</form>
</div>
app.js (where I have ui-router stuff)
.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/payments/make-payment');
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('payments', {
url: '/payments',
templateUrl: 'views/payments.html'
})
.state('activity', {
url: '/activity',
templateUrl: 'views/activity.html'
})
// nested lists
.state('payments.make-payment', {
url: '/make-payment',
views: {
'': {
templateUrl: 'views/make-payment.html'
},
'customers#payments.make-payment': {
templateUrl: 'views/customers.html'
},
'billing#payments.make-payment': {
templateUrl: 'views/billing.html'
},
'method#payments.make-payment': {
templateUrl: 'views/method.html'
});
});
billing.html
<p>{{ctrl.customer.account.name}}</p>
<p>{{ctrl.customer.account.address}}</p>
<p>{{ctrl.customer.account.email}}</p>
<p>{{ctrl.customer.account.phone}}</p>
you can send the selected customer data to a service and pull from the service in the two tabs.
so I guess when you actually select a user from the dropdown or whatever you can call myFactory.setCustomer(data).
and in your other two states you can watch the getCustomer() function in myFactory
.factory('myFactory', myFactory);
function myFactory() {
var customer;
function setCustomer(data) {
customer = data;
}
function getCustomer() {
return customer;
}
//public API
return {
setCustomer: setCustomer,
getCustomer: getCustomer
}
}

How to get value in another controller - Angular JS

I am creating some divs using ng-repeat.
See code below :
.controller('meditationsController', function ($scope, $state, $rootScope, $http) {
var req = {
method: 'POST',
url: 'http://example.com/demo/',
headers: {
'Content-Type': 'application/json'
}
}
// Call API
$http(req).then(function(result) {
var rawData = result.data;
$scope.meditationByCategory = {};
for (var i = 0; i < rawData.length; i++) {
var meditation = rawData[i];
if ($scope.meditationByCategory[meditation.main_title] == undefined) {
$scope.meditationByCategory[meditation.main_title] = {};
$scope.meditationByCategory[meditation.main_title].name = meditation.main_title;
$scope.meditationByCategory[meditation.main_title].meditations = [];
}
$scope.meditationByCategory[meditation.main_title].meditations.push(meditation);
}
});
})
<div ng-repeat="(categoryName, category) in meditationByCategory">
<div class="peacefulness"><p class="para-text">{{category.name}}</p></div>
<a href="" ng-click="goToDetailPage()" class="customlink">
<div class="item-content" ng-repeat="meditation in category.meditations">
<span class="leftSpanStyle">{{meditation.title}}</span>
<span class="rightSpanStyle">
<i class="icon ion-ios-information-outline icon-size"></i>
</span>
</div>
</a>
</div>
I have successfully created the list of divs dynamically according to service response.
Now i want to apply click to each div. and the data that i am getting in service response want to bind the next page. I mean the data on the next page will be dynamic and depend upon cliked div.
please help me to bind the data into another page..
Add a button to your view. Something like:
<span class="rightSpanStyle">
<i class="icon ion-ios-information-outline icon-size"></i>
</span>
<button ng-click="doSomeThing($index)"></button>
And in your controller:
$scope.doSomeThing = function(index){
//do something with category.meditations[index]
//or go to another state: $state.go("myState", {item: category.meditations[index]})
}
Edit:
As you say "want to bind to next page" I assume that you want to navigate to another page. Assuming also that you do so by using angulars ui-router, that means that you want to change state. In that case don't forget to define:
url: /myUrl/:item
for that state in question. You can access the item in the target state / controller with $stateParams.item

Angularjs change view without a click

I am stil new to Angular, but trying, very hard, to get my head round it.
Basically, I just want to move from one view, to another one function is complete. Here is the code:
App.controller('clientLogin', function ($scope, $http, $route) {
$scope.clientLoginBt = function () {
var sun = $('#ClientUsername').val();
var spa = $('#ClientPassword').val()
$http({url: "/sources/",
headers: {"X-Appery-Database-Id": dbid},
params: {where: '{"$and" : [{"username": "' + sun + '"}, {"password" : "' + spa + '"}]}'}})
.success(function (data) {
console.log(data.length);
$scope.clientLogggedin = data;
if (data.length > 0) {
$route.clientLogggedin();
} else {
}
})
.error(function (status) {
console.log('data on fail: ' + status);
});
}
});
Above, if the data comes back with more than one row, the user log is correct, and I just want to change view!
I have tried $location, did not work, and as Angular is really simple to use, in the amount of coding, I cannot see any info on it, other than if you click, it starts a controller.
Here is the HTML:
<div class="row" ng-controller="clientLogin">
<div class="large-12 medium-12">
<input type="text" id="ClientUsername" placeholder="Enter Username" />
<input type="password" id="ClientPassword" placeholder="Enter Password" />
<button ng-click="clientLoginBt()">Login</button>
</div>
</div>
The page I am looking to jump to, within the is called clientLoggedIn.html.
I have also added it to the config, thinking i could access it with $route :
App.config(function ($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: 'views/home.html'
})
.when('/userLogin', {
templateUrl : 'views/userLogin.html',
controller: 'userLoginController'
})
.when('/clientLogin', {
templateUrl : 'views/clientLogin.html',
controller: 'clientLoginController'
})
.when('/clientLoggedIn', {
templateUrl : 'views/clientLoggedIn.html',
controller: 'clientLoggedInController'
})
.otherwise({
redirectTo : '/'
}
);
});
Any ideas on what I am doing wrong please ?
Thanks in advance.
Using path method of $location should do the trick. Since you want to get to clientLoggedIn.html, you would need to use the matching route (/clientLoggedIn):
$location.path("/clientLoggedIn");
Be sure that $location service is injected into your App Controller. This is the line you should probably replace with what I have above:
$route.clientLogggedin();
It is just a matter of checking an indicator whether the $http call was successful or not. If you are not willing to add a routing for clientLoggedIn.html. You can do something like below, just to enable the logged in page:
<div class="row" ng-controller="clientLogin">
<div class="large-12 medium-12" ng-hide="sucessfulLogin">
<input type="text" id="ClientUsername" placeholder="Enter Username" />
<input type="password" id="ClientPassword" placeholder="Enter Password"/>
<button ng-click="clientLoginBt()">Login</button>
</div>
<ng-include src="'views/clientLoggedIn.html'" ng-show="sucessfulLogin">
</ng-include>
<!-- or just include the DOM element here if you do not
want a separate html altogether-->
</div>
and in the REST call:
if (data.length > 0) {
//Assuming the flag in pre-initialized to false in controller
$scope.sucessfulLogin = true;
} else {
}
Also note, using ng-include directive you can still use a separate controller in clientLoggedIn.html if you are willing to. Just have to use ng-controller in the first element inside clientLoggedIn.html.

Resources