简体   繁体   中英

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) {


}

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

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