Angular JS-如何在控制器内调用指令方法



我有名为"学生"的指令,问题是我无法访问指令内的方法,例如,我必须在控制器中调用方法" setText",我该怎么做?

angular.module('sampleApp')
        .directive('student', ['appConfig', '$filter', function(appConfig, $filter) {
          var template  = appConfig.DIRECTIVE_BASE_URL +'/demo/student.html';
          return {
            restrict: 'E',
            replace: true,
            controller: ['$scope', function($scope) {
              $scope.setText = function(a){
                if(a.type === 'manual'){
                  return 'Manually Placed';
                } else {
                  return '';
                }
              };
            }],
            scope: {
              studentData: '=',
              studentName: '='
            },
            templateUrl: template
          };
        }]);

您可以在学生指令的内部定义setText

angular.module('sampleApp')
       .directive('student', ['appConfig', '$filter', function(appConfig, $filter) {
         var template  = appConfig.DIRECTIVE_BASE_URL +'/demo/student.html';
         const setText = function(a) {
           if(a.type === 'manual') {
             return 'Manually Placed';
           } else {
             return '';
           }
         };
         return {
           restrict: 'E',
           replace: true,
           controller: ['$scope', function($scope) {
             $scope.setText = setText;
           }],
           scope: {
             studentData: '=',
             studentName: '='
           },
           templateUrl: template
         };
       }]);

最新更新