cartController in AngularJS:
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
$scope.refreshCart = function() {
$http.get('http://localhost:8080/rest/cart')
.success(function(response) {
$scope.items = response.data;
});
};
$scope.removeFromCart = function(productId) {
$http.delete('/delete/' + productId)
.success(function (data) {
$scope.refreshCart();
});
};
$scope.addToCart = function(productId) {
$http.put('/add/'+ productId)
.then(function(response) {
$scope.refreshCart();
});
};
});
First HTML file (here everything works):
<a href = "#" type="button" class="btn btn-info" th:attr="
ng-click='addToCart(' + ${product.id} + ')'" data-toggle="modal" data-target="#myModal">
Add to cart</a>
Second HTML file:
<html lang="en" xmlns:th="http://www.thymeleaf.org" ng-app="demo">
<script src="http://localhost:8080/cartController.js"></script>
<body ng-controller="Hello">
(...)
<tbody ng-repeat="item in items.cartItemList">
<div class="row">
<h4 class="nomargin">{{item.product.name}}</h4>
<p>{{item.product.description}}</p>
</div>
<td data-th="Price">{{item.price}} PLN</td>
<td data-th="Quantity">{{item.quantity}}</td>
</tbody>
(...)
So what i need to do is:
1) Hit the button in first HTML file, and load JSON to $scope.items (it works).
2) Show the second HTML file, load JSON from $scope.items, and view this JSON to user.
But when I get the second HTML file and try to show data, the $scope.items is empty. Can you help pleae ?
Do you get console errors in your browser? Maybe you have to define items on the controller as empty array like in the example below ...
.controller('Hello', function($scope, $http) {
//define empty array
$scope.items = [];
$scope.refreshCart = function() {
$http.get('http://localhost:8080/rest/cart')
.success(function(response) {
$scope.items = response.data;
});
};
//...
}
I would suggest you to use broadcast and emit. Pass data between the controllers using these. You should use $broadcast if you want to pass data from parent controller to child controller. And emit if the other way around.
Related
ModalInstance data is getting NULL in importing controller.
I have changed modelInstance name also.But dint work out.
here am adding my code,
SaveController.js
scope.open = function (_data) { //data is present
var modalInstanceData = modal.open({
controller: "PopUpController",
templateUrl: 'myModalContent.html',
resolve: {
data: function()
{
return _data; // values are present here
}
}
});
};
PopUpController.js
angular.module('user').controller('PopUpController',
['$scope','$state','$uibModalInstance',
function(scope,state,modalInstanceData,data) {
data={};
scope.data = data;
farmBid.produceValue = scope.data.produceId; //value is present here
}])
Html
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-body">
<input type="text" name="produceValue" ng-model="farmBid.produceValue" />
<!-- But here its not prefilling the data-->
<input type="submit" ng-click="generate(farmBid)">
</div>
</script>
Modal data values are not being visible in HTML page
Please help
You should pass the parameters in right order and should match, you are missing 'data'
angular.module('user').controller('PopUpController',
['$scope','$state','$uibModalInstance','data',
function(scope,state,modalInstanceData,data) {
I have to pass AngularJs object to another Controller when button click event on view.
CHTML
<div ng-repeat="hotel in respData.hotels">
<button type="button" class="btn" data-ng-click="setTab(hotel.code)">Check Availability
</button></div>
Script
$scope.setTab = function (hotelcode) {
var url = 'Hotel';
url += '?HotelCode=' + hotelcode '
window.location.href = url;}
Now i'm passing one value only. I want to pass hotel object as a parameter.
Is their way to do that?
You can pass your whole Hotel object to your first controller and then make use of $emit or $broadcast in order to send that object to another controller. Here's a short example:
One.html
<html ng-app="app">
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script>
var app = angular.module('app', ['ui.router']).config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('two',{
url: '/two',
templateUrl: "two.html",
})
})
app.controller("Parent", function ($scope, $state) {
$scope.send = function (msg) {
$scope.$broadcast('eventName', { message: msg });
$state.go('two')
};
});
app.controller("Child", function ($scope) {
$scope.$on('eventName', function (event, args) {
$scope.message = args.message;
console.log($scope.message);
});
});
</script>
<body ng-app="app">
<h1> Index Page </h1>
<!---
Look at these div tags here, $broadcast is used to transfer content from
Parent to Child Controllers only and $emit for Child to Parent Controller
!--->
<div ng-controller = "Parent" >
<button ng-click = send('Hello')> Send Hello</button>
<div ng-controller = "Child" class="container" ui-view> </div>
</div>
</body>
</html>
Two.html
<body ng-app="app">
<span> Recieved : {{message}}</span>
</body>
$state.go('toState',object);
You can use $state.go to send object values to another controller if you are using ui-router if not you can use emit and broadcast see details here
Working plnkr of broadcast can be found here
app.controller('Parent', function($scope) {
$scope.message="";
$scope.emitedmessage="";
$scope.clickevent=function(){
$scope.$broadcast('transfer',{message:$scope.message});
}
$scope.$on('transferUp',function(event,data){
console.log('on working');
$scope.emitedmessage=data.message;
});
});
app.controller('Child',function($scope){
$scope.message="";
$scope.broadcastmessage=""
$scope.$on('transfer',function(event,data){
$scope.broadcastmessage=data.message;
});
$scope.clickevent=function(){
$scope.$emit('transferUp',{message:$scope.message});
}
});
I have been using $rootScope to save data in my angular app uptil now, but when user refreshes the page the data is lost. Need to change that.
Login Controller
myapp.controller('loginController', function($scope, $rootScope, loginFactory, requestFactory, userFactory, contactFactory, $location, $cookies) {
$scope.getUser = function(){
delete $rootScope.reqMessage;
var user_repack = {
email: $scope.user.email,
password: $scope.user.password
}
loginFactory.getUser(user_repack, function (data){
$rootScope.users = data
$scope.userData = $cookies.userData || {};
$cookies.userData = data
requestFactory.getRecievedRequests(data, function (data){
if(data.length > 0){
$rootScope.recievedRequests = data;
}
})
contactFactory.getContacts(data, function (data){
$rootScope.userContacts = data;
})
$location.path('/dashboard')
})
}
});
Injecting ngCookies
var myapp = angular.module('demo_app', ['ngRoute', 'ngMessages', 'ngCookies']);
});
Front End
<div ng-controller="userController" ng-show="users">
<div class="pull-right" ng-controller="loginController">
<form>
<input type='submit' value='Logout' ng-click='logout()' class="btn btn-danger">
</form>
</div>
<h5 ng-show="welcome">{{welcome}}</h5>
<h2>Hello {{users.name}} {{userData}}</h2>
I have used both $rootScope and $cookies just to try it out. In the front end users.name prints but not userData.
Been trying to figure this out for a while now. any help is appreciated. Thank you.
PS: Im aware this Q has been asked before, i've read through the other posts but couldn't figure it out.
Edit
have tried following the get & put method from the documentation.
var userCookie = $cookies.get('userCookie')
$cookies.put('userCookie', data);
throws an error saying $cookies.get is not a function
I have a page that will show a list of items. The list of items can be be constantly changing, so whenever the use goes to this page or refreshes the page, he would see the new list of items.
I am currently use Parse to store my items and I will use a promise to interact with the Parse API and get my items. A very simplified example is below.
The basic flow is that when index.html is shown, HomeCtrl.js will load and call ItemService.getItems() to get the items, attach them to $scope.items and then display any changes to the view. ItemService.getItems() is a promise provided from the Parse API.
app.js
var myApp = angular.module('myApp',[]);
// Parse API keys
Parse.initialize('MCNXFhdenmpSRN1DU8EJrG3YROXaX4bg0Q5IYwKp', 'XZfWd7J9xGSZQOizu0BoAtIUYtECdci4o6yR76YN');
index.html
<html ng-app = 'myApp'>
<script src="//www.parsecdn.com/js/parse-1.6.2.min.js"></script>
<head>
<title> My Simple Example that doesn't work! </title>
</head>
<body layout="row">
<div ng-controller = "HomeCtrl as ctrl">
<div ng-repeat="item in ctrl.items">
{{item.id}}
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src = "app.js"> </script>
<script src = "HomeCtrl.js"> </script>
<script src = "ItemService.js"> </script>
</body>
</html>
ItemService.js
var myApp = angular.module('myApp');
myApp.service('ItemService', function(){
// gets all Items
this.getItems = function() {
var Item = Parse.Object.extend("Item");
var query = new Parse.Query(Item);
return query.find().then(function(items){
return items;
});
return this;
}
});
HomeCtrl.js
var myApp = angular.module('myApp');
myApp.controller('HomeCtrl',[ 'ItemService', '$scope',function(ItemService, $scope){
$scope.items = [];
ItemService.getItems()
.then(function(results){
$scope.$apply(function() {
$scope.items = results;
console.log($scope.items);
});
});
console.log($scope.items);
}]);
$scope.items does change in the $scope.$apply function (I print it out and can see some items) , however it is not changed for the view. When I print $scope.items after ItemService.getItems(), I print out an empty array.
Am I incorrectly updating $scope.items after calling the promise or is there some concept that I am not understanding?
Any help is appreciated.
EDIT
from 456's answer, I see that I made a mistake in my ng-repeat and his answer works. However I would like to keep using controllerAs syntax. I have tried to update this.items in a $scope.$apply function but it does not work - this.items is modified, but the change is not represented in the view. My modifications are below
index.html
<div ng-controller = "HomeCtrl as ctrl">
<div ng-repeat="item in ctrl.items">
{{item.id}}
</div>
</div>
HomeCtrl.js
var myApp = angular.module('myApp');
myApp.controller('HomeCtrl',[ 'ItemService', '$scope',function(ItemService, $scope){
this.items = [];
ItemService.getItems()
.then(function(results){
$scope.$apply(function() {
this.items = results;
console.log(this.items);
});
});
}]);
The error you are getting is due to the fact that 'this' will point to the window object when the control comes to your then function.
ItemService.getItems()
.then(function(results){
//Here 'this' will point to window
//window.items is undefined
});
Hence the error.
You can solve this in many ways,one of which is using another object to point to this.
var myApp = angular.module('myApp');
myApp.controller('HomeCtrl',[ 'ItemService', '$scope',function(ItemService, $scope){
var that = this;
that.items = [];
ItemService.getItems()
.then(function(results){
that.items = results;
});
}]);
Try this if it works for you.
U should call it in html like this-
<div ng-repeat="item in items">
I have a file (courses.json) that I want to remove courses from when I click on the 'x' next to the course-name. I am very much a beginner at this, and I can't really get it to work.I have no problem reading from the file, but nothing happens when I click the 'x'. Very grateful for all the help I can get!
This is my code:
var app = angular.module('myApp', []);
app.controller('courses', function($scope, $http) {
$http.get("courses.json").success(function(data) {
$scope.courses = data.kurser;
});
});
function courses($scope, courses) {
$scope.deleteItem = function (key) {
delete $scope.courses[key];
}
}
HTML:
<div ng-app="myApp">
<ul ng-controller="courses">
<li ng-repeat="(key, value) in courses" id="course-{{value.courseId}}">
{{value.courseName}} <a ng-click="deleteItem(key)">x</a>
</li>
</ul>
</div>
You should define deleteItem method in the same controller where you load data, otherwise courses function is not linked to the application anyhow:
app.controller('courses', function($scope, $http) {
$http.get("courses.json").success(function(data) {
$scope.courses = data.kurser;
});
$scope.deleteItem = function (key) {
delete $scope.courses[key];
}
});