akaphenom
akaphenom

Reputation: 6886

Inject a variable into an Angular Controller from a Angular Directive

Updating as there is some confusion as to what I am asking. I would like to use a directive to inject a variable into the controller used by that directive. I realize I can use the $scope for that, but I don't find that an intuitive solution.


Essentially I want my controller to have the proposal variable injected into it.

My intended usage:

<blah-directive proposal="proposal"></blah-directive>

The directive (so far):

app.directive('blahDirective', function () {
    return {
        restrict: 'E'
        , transclude: true
        , replace: true
        , scope: {
            proposal: '='
        }
        , templateUrl: 'blahTemp.html'
        , controller: blahController
    };
});

blahTemp.html

<form class="form-horizontal" role="form" name="myBidForm">
    **{{ proposal }}**    
</form>

this is displaying the value proposal variable in the $scope fine, but it is not what I want. Essentially I would like to define my controller like:

var blahController = function($scope, SomeOtherResource, proposal) {


}

Upvotes: 1

Views: 1481

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32397

If you want to inject locals into a controller use $controller.

Here is an example (plunker):

app.directive('blahDirective', function ($controller) {
  return {
    restrict: 'E',
    scope: {
      proposal : "="
    },
    transclude: true,
    replace: true,
    templateUrl: 'blahTemp.html',
    link : function (scope, elm, attrs){
      scope.proposal = {};
      var locals = {
        $scope: scope , 
        proposal: scope.proposal
      };
      $controller('blahController', locals);
    }
  };
});

Upvotes: 3

Related Questions