AngularJS контроллер возвращает форму
Разработчики!
Я решил попробовать Angular, поэтому я хочу сделать простое приложение для загрузки и редактирования изображений, в MVC
(или близко к нему) архитектура.
И я застрял на входе, потому что я действительно не знаю, как правильно вернуть заполненный main form
из шаблона.
Пока думаю пока - звоню controller
сначала функция, затем она должна вызвать mainService
функция, которая создает форму, которая использует 'imageUploadController', который использует imageUploadService
,
Но я кое-что говорю мне, что нехорошо делать такие вещи.
Моя главная проблема - как добраться uploadImageForm.html
Передайте это index.html
, без ссылок или включений (я просто хочу держать вещи отдельно), убедитесь, что службы и контроллеры там работают должным образом
Как лучшие практики выглядят в той же ситуации?
Вот код, надеюсь, это поможет увидеть проблему, которую я получил более четко:
Вот мой index.html
<!doctype html>
<html lang="en" ng-app="modernFilter">
<head>
<meta charset="utf-8">
<title>Modern.Filters</title>
<script src="asstes/libs/angular.min.js"></script>
<script src="app/components/app.js"></script>
<script src="app/shared/imageUploadController.js"></script>
</head>
<body ng-controller = "mainController">
<span>{{mainForm}}</span>
</body>
</html>
Вот app.js
'use strict';
// Define the `modern.filter` module
var modernFilterApp = angular.module('modernFilter', []);
// Define main controller
modernFilterApp.controller('mainController', ['$scope', function($scope, mainService){
// Stores form data
$scope.mainForm = null;
// Returns main form template
$scope.getMainForm = function(){
$scope.mainForm = mainService.getMainForm();
}
// Call function on documentready
angular.element(document).ready(function () {
$scope.getMainForm();
//todo: is it even okay? but without it nothing happens
$scope.$apply();
})
}]);
// Define service
modernFilterApp.service('mainService', function(mainService){
this.getMainForm = function(){
// todo: how should I get template here?
return "filled form template from here"
}
});
Также я получил шаблон imageUploadView
<div ng-controller="imageUploadController">
<canvas id="imageCanvas"></canvas>
<form action="">
<input my-upload type="file" name="upload" onchange="angular.element(this).scope().uploadImage()">
</form>
Cotroller и сервис для него (с примером кода, все еще отлаживая его)
modernFilterApp.controller('imageUploadController', ['$scope', 'imageUploadService', function($scope, imageUploadService) {
// Stores image
$scope.image = null;
// Returns main form template
$scope.uploadImage = function() {
$scope.image = imageUploadService.handleImage(arguments);
}
}]);
// Define upload service
modernFilterApp.service('imageUploadService', function(imageUploadService) {
// Function handles uploaded files (dirty code)
this.handleImage = function(event) {
var canvas = angular.element('#imageCanvas'),
context = canvas.getContext('2d'),
reader = new FileReader(),
img = new Image();
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0);
img.src = event.target.result;
return reader.readAsDataURL(e.target.files[0]);
}
}]);
1 ответ
Не пытайтесь получить шаблон из контроллера.
Вам нужно использовать директиву. Создайте директиву со своим контроллером как imageUploadController, его шаблон как imageUploadView и включите его в index.html
Ваш HTML:-
<body ... >
<my-directive></my-directive>
</body>
//include directive file,controller files
Директива:-
.directive('myDirective', ['your service',function(your service) {
return {
restrict: 'E',
transclude: true,
scope: {},
templateUrl: 'template url',
link: function (scope) {
},
controller : function($scope){
//your controller
}
};
}]);
HTML будет автоматически отображаться вместо директивы