2015-06-08 72 views
1

我想從指令調用父函數。但是我的功能沒有被調用。Angular指令不調用父範圍函數

以下是供您參考的代碼。

控制器

'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> 
+0

也使用範圍$ eval而非範圍$ apply – harishr

回答

1

內,您的指令代碼,您所呼叫ONSELECT使用到scope.onSelectattrs.onSelect改變它。 attrs.onSelect只會給你字符串值iconSelected()。您需要在由指令創建的隔離範圍中可用的函數引用。

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

當然!非常感謝Shankar :) – Moon

相關問題