Ich las Digging into Angular's "Controller as" syntax Artikel. Es zeigt unten Snippet, um "Controller als" -Syntax in Direktive zu verwenden.Wie definiert man allgemeine Anweisungen in controllerAs Syntax?
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() {}
};
});
Hier muss ich Controller-Name controller
Eigenschaft festlegen. Wenn ich jetzt eine gemeinsame Direktive definieren möchte, die ich in mehreren Controllern verwenden möchte, wie kann ich das tun?
Edit 1:
Ich veröffentliche den Code über das, was ich erreichen will. In der Ansicht gibt es ein Eingabe-Tag für die Datei und wenn die Datei ausgewählt ist, möchte ich den Namen und Inhaltstyp. Ich werde das Änderungsereignis des Eingabe-Tags verwenden. Ich weiß nicht, wie ich das Dateiobjekt an mein vm übergeben kann. Ich möchte diese Direktive verwenden, die Change Event verwendet, um Informationen über die Datei in mehreren Controllern zu erhalten.
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();
});
}
};
});
Bitte die bearbeitete Frage prüfen. – Xyroid