У меня проблема с вызовом функции из углового - эта функция выполняет две разные вещи, загружая изображение в s3 и сохраняя данные из формы и URL-адреса изображения в s3 в монго. вот мой html, поэтому я назвал fucntion ng-submit:
<form class="form-group" ng-submit="createActivity()">
<div class="form-group">
<div class="col-sm-10">
<label for="inputEmail3" class="col-sm-2 control-label">Title:</label>
<input class="form-control" type="text" placeholder="Title" ng-model="title"></input>
</div>
<div class="col-sm-10">
<label for="inputEmail3" class="col-sm-2 control-label">Age:</label>
<input class="form-control" id="inputEmail3" type="number" placeholder="Age" ng-model="age" min="0" max="16"></input>
</div>
<div class="col-sm-10">
<label for="inputEmail3" class="col-sm-2 control-label">Description:</label>
<textarea class="form-control" id="inputEmail3" type="text" placeholder="Description" ng-model="description"></textarea>
<br>
</div>
<div class="col-sm-10">
<label for="inputEmail3" class="col-sm-2 control-label">Themes:</label>
<input type="radio" name="themes" value="frozen" ng-model="theme">frozen
<input type="radio" name="themes" value="minions" ng-model="theme">minions
<input type="radio" name="themes" value="heroes" ng-model="theme">heroes
<input type="radio" name="themes" value="princess" ng-model="theme">princess
<input type="radio" name="themes" value="piraets" ng-model="theme">piraets
<input type="radio" name="themes" value="none" ng-model="theme">none
<br>
</div>
<div class="col-sm-10">
<br>
<input type="file" name="upload" ng-model="image"></input>
</div>
<div class="col-sm-10">
<br>
<input type="submit" class="btn btn-default" name="send"></input>
</div>
</div>
</form>
и вот функция:
$scope.createActivity = function() {
var myUrl;
function(req, res) {
var ext, hash, form = new formidable.IncomingForm(),
files = [],
fields = [];
form.keepExtensions = true;
form.uploadDir = 'tmp';
form.on('fileBegin', function(name, file) {
ext = file.path.split('.')[1];
hash = hasher();
file.path = form.uploadDir + '/' + hash;
});
form.on('field', function(field, value) {
fields.push([field, value]);
}).on('file', function(field, file) {
files.push([field, file]);
}).on('end', function() {
fs.readFile(__dirname + '/../../tmp/' + hash, function(error, buf) {
var req = client.put('/images/' + hash + '.png', {
'x-amz-acl': 'private',
'Content-Length': buf.length,
'Content-Type': 'image/png'
});
console.log("hello");
fs.writeFile(__dirname + '/../../downloads/' + hash + '.png', buf, function(err) {
if(err) {
return console.log(err);
}
});
myUrl = req.url;
req.on('response', function(res) {
image.save(function(error, result) {
if(error) {
console.error(error);
} else {
response.redirect('http://' + request.headers.host + '/' + hash);
};
})
});
req.end(buf);
});
});
form.parse(request);
activity.title = $scope.title;
activity.age = $scope.age;
activity.description = $scope.description;
activity.theme = $scope.theme;
activity.image = myUrl;
activity.$save(function(result) {
$scope.activities.push(result);
$scope.title = '';
$scope.age = '';
$scope.description = '';
$scope.theme = '';
$scope.image = myUrl;
});
}
}]);
Я должен сказать, что индивидуальность каждой функции сама по себе работает, но когда я помещаю ее в одну функцию, это не так. (Я присоединился к ним вместе, потому что хочу, чтобы оба они были вызваны из моей формы).
То, как мы это делаем, - это метод функции, который вы описываете:
...
formClickDoSomething() {
this.functionOne();
this.functionTwo();
this.functionThree();
}
...
Он должен работать, предполагая, как вы говорите, все три функции работают самостоятельно.
Вы не должны присоединяться к двум функциям в 1 подобном. Храните функции appart и вызывайте их как из другой функции, так и для лучшей читаемости. Вот общий пример:
function createActivity() {
doSomethingFirst();
doSomethingNext();
}
function doSomethingFirst() {
// your code for first function
}
function doSomethingNext() {
// your code for next function
}
Или, если вы вызываете свою вторую функцию после успешного завершения вызова из первой функции, вы можете сделать что-то вроде этого:
function createActivity() {
// your code for first function
if (success) {
doSomethingNext();
} else {
// show error
}
}
function doSomethingNext() {
// your code for next function
}