0

I have templated my Angular app with Yeoman, so my app directory structure is nice and neat and will give you an idea of how my project is constructed. I have 2 routes in my app, one is called 'main' and the other 'sub'.

When I'm in my 'main' view, I have a link that then forwards the user to the 'sub' view. How can I pass a simple value to the 'sub' controller through the link from my 'main' view?

i.e. my link is just a standard html link:

<a href="/#/sub">Go to sub</a>

When you hit that the sub.js controller can add some data to $scope for the sub view and so on. I want to access the value in the 'sub' controller that was passed from the 'main' view... Hope that makes sense..

2 Answers 2

2

From what I understand you basically want to communicate between two controllers.
The first instinct might be to create a parent scope and bind data to it, but there is a better way, a service.

You bind data to this service and it can act as the messenger between your controllers, like so:

angular.module('app', [])

  .factory('Data', dataService)

  .controller('firstController', firstController)
  .controller('secondController', secondController);

function dataService() {
  return { message: "I'm data from a service" };
}

function firstController($scope, Data) {
  $scope.data = Data;
}

function secondController($scope, Data) {
  $scope.data = Data;
}

And markup:

<h2>First controller</h2>
<div ng-controller="firstController">
  <input type="text" ng-model=data.message  />
  {{ data.message }}
</div> 

<h2>Second controller</h2>
<div ng-controller="secondController">
  <input type="text" ng-model=data.message  />
  {{ data.message }}                        
</div>   

Demo Explained very good at egghead.io

Sign up to request clarification or add additional context in comments.

Comments

1

bind the variable dataToFoward which is a $scope variable in mainCtrl

<a ng-href="#/sub/{{dataToFoward}}">Go to sub</a>

in routes,

when("/sub/:sampleData", {templateUrl: "pathToTemplate" }).

in Sub Controller,

app.controller('subCtrl', function($routeParams,$scope) {
    $scope.fromMain = $routeParams.sampleData;
});

3 Comments

In the link, do I HAVE to use 'ng-href' or is a normal 'href' also fine?
its good to use ng-href because may be $scope.dataToFoward variable is not set in the controller when you clicking the link.
if $scope.dataToFoward not set when you clicking the link href="#/sub/{{dataToFoward}}" will result in a 404 error, but ng-href="#/sub/{{dataToFoward}}" is acting as link only afterdataToFoward is set , it will not clickable before the dataToFoward is set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.