AngularJs - 如何在指令中访问控制器的功能和模型

时间:2018-04-24 11:59:44

标签: angularjs

嗨我已经多次指示了指令,每次我必须绑定每个属性,功能等等。

app.directive('postJobWizard', function () {

return {
    restrict: 'EA',
    scope: {
        'artistSearchModel': "=",
        'showDropdown': "=",
        'operaticRoleSearchResult': "=",
        'viewAllJobs': "&",
        'getSingleJob':"&",
        'musicalWorkSearchResult': "=",
        'institutionSearchResult': "=",
        'changeTypeOfFilter': "&",
        'searchArtistJob': "&",
        'placeOfSearch':"@placeOfSearch",
        'artistFilterSearch':'=',
        'dropDownTitles':'=',
        'searchPlaceHolder':'@searchPlaceHolder',
        'isArtistOrAos':'=',
        'noResultFound' : '=',
        'oppurtunityOrBoard':'@',
        'oppurtunitiesOrBoards':'@',
        'showInfoIcon' : '=',
        'infoIconText' : '='
        },
    controller: function () { },
    controllerAs: '$postJob',
    bindToController: true,
    templateUrl: '/views/tss/directives/postJobWizard.html'
};

});

但是假设我有50个函数和100个模型,我必须在scope中编写每个函数。是否有任何方法或最佳实践可以访问父母控制器功能和模型。请解释这是最佳做法吗?

2 个答案:

答案 0 :(得分:1)

像这样注入常数:

app
.constant('scopeSettings',{your scope object goes here (probably on a seperate file)})
.directive('postJobWizard', function (scopeSettings) {

return {
    restrict: 'EA',
    scope: scopeSettings,
    controller: function () { },
    controllerAs: '$postJob',
    bindToController: true,
    templateUrl: '/views/tss/directives/postJobWizard.html'
  };
});

答案 1 :(得分:1)

我制作了一个小片段,希望能让你朝着正确的方向前进。另请查看this链接,了解有关指令以及示波器和控制器如何工作的更多信息。

(function() {
	'use strict';
  
  angular.module('myApp', []);
  
  angular.module('myApp').controller('MyController', MyController);
  
  MyController.$inject = [];
  function MyController() {
  	var main = this;
    
    main.thisFunctionIsPublic = thisFunctionIsPublic;
    
  	function thisFunctionIsPublic() {
    	return 'This text comes straight from the parent controller!';
    }
  
  	function thisFunctionIsPrivate() {
    	return 'private!';
    }
  }
  
  angular.module('myApp').directive('myDirective', function() {
  	return {
    	restrict: 'E',
      scope: false,
      controllerAs: '$controller',
      //bindToController: true,
      template: '<p>Public function: {{$controller.parentController.thisFunctionIsPublic()}}</p><p>Private function: {{$controller.parentController.thisFunctionIsPrivate()}}</p>',
      controller: function($element) {
      	this.parentController = $element.parent().controller();
        console.log(this.parentController);
      }
    };
  });
  
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
  <div ng-controller="MyController as main">
    <my-directive></my-directive>
  </div>
</body>

免责声明:我不认为这是最佳做法,因为我认为指令应该主要是独立的代码片段,无论父控制器上有什么内容都应该能够工作,但是这个如果我真的需要,我将如何访问父控制器。