Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variables to AngularJS controller, best practice?

I am brand new to AngularJS and like what I've seen so far, especially the model / view binding. I'd like to make use of that to construct a simple "add to basket" piece of functionality.

This is my controller so far:

function BasketController($scope) {     $scope.products = [];      $scope.AddToBasket = function (Id, name, price, image) {          ...      }; } 

And this is my HTML:

<a ng-click="AddToBasket('237', 'Laptop', '499.95', '237.png')">Add to basket</a> 

Now this works but I highly doubt this is the right way to create a new product object in my model. However this is where my total lack of AngularJS experience comes into play.

If this is not the way to do it, what is best practice?

like image 845
Greg Avatar asked Jul 28 '12 18:07

Greg


People also ask

What is the efficient way of sharing data between controllers?

Approach: To share data between the controllers in AngularJS we have two main cases: Share data between parent and child: Here, the sharing of data can be done simply by using controller inheritance as the scope of a child controller inherits from the scope of the parent controller.

What is $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods.

Why $scope is used in AngularJS?

Scopes provide APIs ($apply) to propagate any model changes through the system into the view from outside of the "AngularJS realm" (controllers, services, AngularJS event handlers). Scopes can be nested to limit access to the properties of application components while providing access to shared model properties.


1 Answers

You could use ng-init in an outer div:

<div ng-init="param='value';">     <div ng-controller="BasketController" >         <label>param: {{value}}</label>     </div> </div>   

The parameter will then be available in your controller's scope:

function BasketController($scope) {         console.log($scope.param); } 
like image 81
Andrejs Avatar answered Oct 09 '22 06:10

Andrejs