2016-09-07 25 views
0

我正在閱讀Digging into Angular's "Controller as" syntax文章。它顯示下面的代碼片段,在指令中使用「Controller as」語法。如何在controllerAs語法中定義通用指令?

app.directive('myDirective', function() { 
    return { 
    restrict: 'EA', 
    replace: true, 
    scope: true, 
    template: [].join(''), 
    controllerAs: '', // woohoo, nice and easy! 
    controller: function() {}, // we'll instantiate this controller "as" the above name 
    link: function() {} 
    }; 
}); 

這裏我要設置控制器名稱controller屬性。現在,如果我想定義我想在多個控制器中使用的通用指令,我該怎麼做?

編輯1:

我張貼什麼我想要實現的代碼。鑑於,有一個文件的輸入標籤,當選擇文件時,我希望它的名稱和內容類型。我將使用輸入標籤的更改事件。我不知道如何將文件對象傳遞給我的虛擬機。我想使用該指令使用更改事件來獲取有關多個控制器中的文件的信息。

的index.html

<!DOCTYPE html> 
<html lang="en" ng-app="myApp"> 
<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script> 
    <script src="/myCtrl.js"></script> 
</head> 

<body ng-controller="MyController as vm"> 
    <input name="file" type="file" file /> 
    <input type="button" ng-click="vm.upload(vm.file);" value="Upload" /> 
</body> 
</html> 

myCtrl.js

var app = angular.module('myApp', []); 

app.controller('MyController', MyController); 

MyController.$inject = ['$http']; 

function MyController($http) { 
    var vm = this; 

    vm.file = null; 
    vm.upload = function(file) { 
     $http.post('/upload', { filename: file.name, contentType: file.type }) 
     .success(function(resp) { 
      console.log(resp); 
     }) 
     .error(function(resp) { 
      console.log(resp); 
     }); 
    } 
} 

app.directive('file', function() { 
    return { 
    restrict: 'AE', 
    scope: true, 
    controllerAs: 'vm', 
    link: function(scope, el, attrs){ 
     el.bind('change', function(event){ 
     var files = event.target.files; 
     var file = files[0]; 

     // What to write here to pass file object into vm ? 

     // Below line is for that controller design which uses $scope service. But I am using controllerAs syntax 
     // scope.file = file; 
     // scope.$apply(); 
     }); 
    } 
    }; 
}); 

回答

0

,然後定義了無控制器的指令(可選)。

IMP:與scope: true定義指令或default scope離開它,但沒有定義isolated scope。 這將允許指令繼承父控制器中定義的方法和屬性。

並將模板中的指令放入ng-controller指令中。

控制器1:

<div ng-controller='ctrl1"> 

    <my-directive></my-directive> 
<div> 

控制器2:

<div ng-controller='ctrl2"> 

    <my-directive></my-directive> 
<div> 

第n個的方式。

EDIT1:

在控制器(MyController):你可以使用$broadcast

vm.upload = function(fileObj){ 

    $rootScope.$broadcast('sending-file-object',{data:fileObj}) 
} 

會收到使用$on所有其他控制器,

$scope.$on('sending-file-object',function(event,data){ 
    console.log(data) // here you get data; 
}) 
+0

請檢查編輯的問題。 – Xyroid

相關問題