Angular指令不调用父作用域函数

时间:2015-06-08 14:16:26

标签: angularjs angularjs-directive

我试图从指令中调用父函数。但是我的功能没有被调用。

以下是供您参考的代码。

控制器

'use strict';

angular.module('myApp')
  .controller('MyCtrl', function($scope) {
    $scope.iconSelected = function() {
      console.log('iconSelected');

      var icon = angular.element('#icon').prop('files');

      if (!icon) {
        return;
      }

      icon = icon[0];

      var _URL = window.URL || window.webkitURL;
      $scope.utility.icon = _URL.createObjectURL(icon);
    }

    $scope.sourceSelected = function() {
      console.log('sourceSelected');

      var source = angular.element('#source');
      console.log(source.prop('files'));
    };
  });

指令

'use strict';

angular.module('myApp')
  .directive('uploadButton', function() {
    return {
      templateUrl: 'app/directives/upload-button/upload-button.html',
      restrict: 'E',
      transclude: true,
      scope: {
        onSelect: '&'
      },
      link: function(scope, element, attrs) {
        scope.name = attrs.name;
        scope.id = attrs.id || attrs.name;
        scope.label = attrs.label || attrs.name;
        scope.accept = attrs.accept;

        scope.showDialog = function() {
          element.find('#' + scope.id).trigger('click');
        };

        element.find('input').change(function() {
          scope.$apply(attrs.onSelect);
        });
      }
    };
  });

指令模板

<md-input-container class="upload-button">
  <md-button class="md-raised" ng-click="showDialog()">
    <span ng-transclude></span>
  </md-button>
  <input type="file" name="{{name}}" id="{{id}}" aria-label="{{label}}" accept="{{accept}}">
</md-input-container>

指令用法

<upload-button name="icon" on-select="iconSelected()" accept=".svg">Choose an icon</upload-button>
<upload-button class="source-btn" name="source" on-select="sourceSelected()" accept=".zip">Select source code</upload-button>

1 个答案:

答案 0 :(得分:1)

在您的指令代码中,您使用attrs.onSelect调用onSelect将其更改为scope.onSelectattrs.onSelect只会为您提供字符串值iconSelected()。您需要函数引用,该引用将在指令创建的隔离范围中提供。

element.find('input').change(function() {
  scope.$apply(scope.onSelect);
});
相关问题