This question already has answers here:
Can one AngularJS controller call another?
(14 answers)
Closed 9 years ago.
How do I store the items I've selected in a checkbox with other controllers?
My attempt (see the plnkr for views):
script.js (controllers)
var myApp = angular.module('myApp', []);
myApp.factory('CooSelection', function () {
return {selectedCoo: []}
})
function CooListCtrl($scope, CooSelection) {
$scope.coos = {"Coos": ["spark", "nark", "hark", "quark"]};
$scope.coo_list_selection = CooSelection;
$scope.checkSelection = function (item) {
if ($scope.coo_list_selection.indexOf(item) === -1) {
$scope.coo_list_selection.push(item);
} else {
$scope.coo_list_selection.splice($scope.coo_list_selection.lastIndexOf(item), 1);
}
}
}
CooListCtrl.$inject = ['$scope', 'CooSelection'];
function DebugCooList($scope, CooSelection) {
$scope.coo_selection = CooSelection;
}
DebugCooList.$inject = ['$scope', 'CooSelection'];
When you reference the CooSelection service, you are expecting an array, but the factory returns an object. You could do this instead:
myApp.factory('CooSelection', function () {
return []; // Return an array instead of an object.
})
Also, in your DebugCooList controller, your scope property does not match the name of the variable you are checking in the view. The controller code assigns to coo_selection but the view checks coo_list_selection, so you'll need to change one to match the other.
Related
This question already has answers here:
Passing data between controllers in Angular JS?
(18 answers)
Closed 6 years ago.
Below this code console.log is working properly. How to set this data another page using another controller.
$scope.selectedJsonObject=function(category)
{
console.log(category);
}
You can use Service to share the variable across two controllers,
angular.module('Shared', []);
angular.module("Shared").factory("myService", function(){
return {sharedObject: {data: "eran" } }
});
angular.module('Shared').controller('MainCtrl', function ($scope, myService) {
$scope.myVar = myService.sharedObject;
});
angular.module('Shared').controller('Secondtrl', function($scope, $http, myService) {
$scope.myVar = myService.sharedObject;
});
Working App
This question already has answers here:
Share data between AngularJS controllers
(11 answers)
Closed 7 years ago.
I've been testing Angularjs for a project and I would like to know how to capture data on a controller from view and pass this data to another controller.
This pseudocode exemplifies what I want to do:
controller1('$scope', function($scope){
var val1 = $scope.dataFromView;
});
controller2('$scope', function($scope, controller1 ){
var val2 = controller1.val1;
//then do something with val1
});
You should use factories for this
app.factory('val1', function() {
// Your code goes here
});
And then in the controller, inject the factory.
app.controller('controller1', ['val1', function(val1) {
}]);
app.controller('controller2', ['val1', function(val1) {
}]);
This question already has answers here:
Angular - extending $resource subobject with custom methods
(4 answers)
add a custom function on angular $resource [duplicate]
(3 answers)
Closed 7 years ago.
I'd like to get objects from a server, something like:
var User = $resource('/user/:userId', {userId:'#id'});
I'd like User instances to all have certain methods to calculate derived data, without the server having to return it. For example, say for:
var aUser = User.get({userId: 43});
The server returns something like:
{id: 43, name: "Bob", alertTimestamp: 1447365544}
I'd like to be able to do something like:
if (aUser.alertTimePassed()) {
// do stuff
}
Is there a clean way to do this short of something like this, which seems hacky?
var alertTimePassed = function () {
var now = (new Date()).getTime() / 1000;
return now >= this.alertTimestamp;
};
var User = $resource('/user/:userId', {userId: '#id'}, {
get: {
method: "GET", url: '/user/:userId',
transformResponse: [angular.fromJson, function (obj) {
obj.alertTimePassed = alertTimePassed;
}]
}
});
If you create your $resource using a factory you can modify the $resource object before returning it from the factory.
app.factory('User', function ($resource) {
var User = $resource('/user/:userId', {userId: '#id'});
// add any methods here using prototype
User.prototype.alertTimePassed = function() {
// do stuff
};
return User;
});
I am trying to get the http request result to my child controller.
I have something like
<div ng-controller = "parentCtrl">
<button ng-click="callApi()">click me</button>
<div ng-controller = "childCtrl">
<div>{{productDetail}}</div>
</div>
</div>
angular.module('App').controller('parentCtrl', ['$scope','myFactory',
function($scope, myFactory) {
$scope.callApi = function() {
myFactory.request(id)
.then(function(data) {
$scope.productDetail = data
//do something in parent controller here....
})
}
}
]);
angular.module('App').controller('childCtrl', ['$scope',
function($scope) {
//I am not sure how to get the productDetail data here since it's a http request call.
}
]);
angular.module('App').factory('myFactory', function($http) {
var service = {};
service.request = function(id) {
return createProduct(id)
.then(function(obj) {
productID = obj.data.id;
return setProductDetail(productID)
})
.then(getDetail)
.then(function(productDetail) {
return productDetail.data
})
}
var createProduct = function(id) {
return $http.post('/api/product/create', id)
}
var setProductDetail = function(id) {
return $http.post('/api/product/setDetail', id)
}
var getDetail = function() {
return $http.get('/api/product/getDetail')
}
return service;
});
I was able to get the request result for my parentCtrl but I am not sure how to pass it to my child controller. Can anyone help me about it?
Thanks!
Potential approaches:
1) Inject myFactory into the child controller as well.
2) Access the parent scope directly from within childCtrl:
$scope.$parent.productDetail
3) If wanting to access from HTML
$parent.productDetail
Above assumes you are wanting to access that value specifically separate from a potential version on the child scope (existing code doesn't show that).
If it's a child scope, and nothing on the child scope (or a scope in between) is named productDetail, and you're not setting a primitive value in the child scope with that name, then you should be able to see the value directly through prototypical inheritance (but any of the three scenarios listed could force the need for a reference through the parent).
following AngularJS in 60 minutes I'm trying to add factory to current code.
I have lineman angular app where angular is declared as follows:
angular.module("app", ["ngResource", "ngRoute"]).run(function($rootScope) {
// adds some basic utilities to the $rootScope for debugging purposes
$rootScope.log = function(thing) {
console.log(thing);
};
});
I want to add the following code but running into JS syntax issue
.factory('simpleFactory', function () {
var factory = {};
var customers = [];
factory.getCustomers = function () {
return customers;
};
return factory;
}
What's the right syntax to merge these 2 blocks? Also should I do mimic controllers directory to create factory or should I really add to the first block? Thanks
Technically you have already merged a certain block from another:
angular.module("app", ["ngResource", "ngRoute"])
.run(function($rootScope) {
// adds some basic utilities to the $rootScope for debugging purposes
$rootScope.log = function(thing) {
console.log(thing);
};
});
for your chain to continue invoking another method such that the "second block" you are talking about(technically its the third block right now), do not terminate the method invocation then simply remove the terminator ; and append the third block.
It must look like this:
angular.module("app", ["ngResource", "ngRoute"]).run(function($rootScope) {
// adds some basic utilities to the $rootScope for debugging purposes
$rootScope.log = function(thing) {
console.log(thing);
};
})
.factory('simpleFactory', function () {
var factory = {};
var customers = [];
factory.getCustomers = function () {
return customers;
};
return factory;
});
Note: Your third method invocation factory() was not closed properly, it lacks the closing parenthesis ) and the terminator symbol ;.
Make sure you chain the factory to your variable. It seems you broke your chain right now.