如何将"控制器传递为xx"参数xx成指令?

时间:2014-08-27 15:50:58

标签: angularjs

在我的代码中,我目前有这个:

<button id="retrieveButton"
   ng-disabled="!home.forms.grid.$pristine"
   ng-click="exam.retrieve(exam.configService.admin.examStatusId, exam.configService.admin.examTypeId, 1)">
   Retrieve
   <span class="fa fa-fw mlr75"
      ng-class="{'fa-spin fa-spinner': exam.stateService.action['retrieve'], 'fa-download': !exam.stateService.action['retrieve'] }">
   </span>
</button>

<button id="retrieveButton"
   ng-disabled="!home.forms.grid.$pristine || content.stateService.action['init']"
   ng-click="content.retrieve(content.configService.admin.contentCreatedBy, content.configService.admin.contentModifiedBy, content.configService.admin.contentStatusId, content.configService.admin.contentTypeId, 1  )">
   Retrieve
   <span class="fa fa-fw mlr75"
      ng-class="{'fa-spin fa-spinner': content.stateService.action['retrieve'], 'fa-download': !content.stateService.action['retrieve'] }">
   </span>
</button>

以及更多..除了考试之外的所有内容都是相同的......来自控制器的内容等为xxxx。

我想创建一个可以用来用通用模板替换代码的指令。这就是我创造的:

app.directive('adminRetrieveButton', ['stateService', function (stateService) {
    return {
        scope: true,
        restrict: 'E',
        template: "<button id='retrieveButton'\
                           ng-disabled='!home.forms.grid.$pristine'\
                           ng-click='exam.retrieve(exam.configService.admin.examStatusId, exam.configService.admin.examTypeId, 1)' >Retrieve\
                   <span class='fa fa-fw mlr75'\
                           ng-class='{\"fa-spin fa-spinner\": exam.stateService.action[\"retrieve\"], \"fa-download\": !exam.stateService.action[\"retrieve\"] }' >\
                            </span>\
                        </button>",
        link: function (scope, element, attrs) {
            scope.stateService = stateService;
            scope.entity = attrs["entity"];
        }
    };
}]); 

我认为这会完成这项工作,但我如何通过考试或内容或..我认为与$ scope.exam或$ scope.content相同?

1 个答案:

答案 0 :(得分:0)

您可以将控制器作为指令的属性传递。

<admin-retrieve-button ctrl="exam"></admin-retrieve-button>

然后在你的指令中你必须这样做:

return {
  scope: {ctrl: '=' }
  ...
}

在模板中,您可以使用ctrl

访问控制器
<button id='retrieveButton' ng-click='ctrl.retrieve( ... , 1)'>