Prometheus
Prometheus

Reputation: 33625

Angularjs how to pass data from a controller to a directive

I have a controller which gets activated by a route (see below) I would like to create a directive that uses this data (once loaded) but I have no idea how to pass this data/bind it.

This is my controller:

app.controller("CampaignData" , ['$scope', 'Restangular', 'CbgenRestangular', '$http', '$q',
    function($scope, Restangular, CbgenRestangular, $http, $q){

       var campaign_call = CbgenRestangular.one('api/v1/campaign', "testcamp").get();

       $q.when(campaign_call.then(
        function(campaign) {
            $scope.campaign = campaign;
            console.log(campaign);
            }
        ))
        .then(function(){

             var cars = $http({method: 'GET', url:$scope.campaign.carlot});
              cars.then(function(reward){
             // do success things here
             console.log(reward.data)
              },
             function(reward){
             //do error things here
             });

        })

         }]);

Then in my template I want to do something like this

{{ campaign.name }}  {{ car.name }}

or even this

<campaign="name"></campaign> 
<campaign="car.name"></campaign>

How can this be done?

Upvotes: 1

Views: 347

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67296

I would not like to create a directive that uses this data

There is no need to create a directive. Once you declare a template and controller in the route config, all the scoped properties within the controller will become active for the template.

Interpolation like this should then work fine:

<div>{{ campaign.name }}</div>
<div>{{ car.name }}</div>

If you wanted to handle a click event on one of the divs, it would look like this:

<div ng-click="myFunctionInController(campaign.name)">{{ campaign.name }}</div>

This function would then be defined in the controller like this:

$scope.myFunctionInController = function(name) {

    console.log(name);
}

Upvotes: 4

Related Questions