简体   繁体   中英

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM