Skip to content

Instantly share code, notes, and snippets.

@wgroeneveld
Created May 29, 2013 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wgroeneveld/5669593 to your computer and use it in GitHub Desktop.
Save wgroeneveld/5669593 to your computer and use it in GitHub Desktop.
angularjs jquery form plugin custom directive
'use strict';
angular.module('uploadComponentModule', [])
.directive('uploadComponent', ['Alert', function(Alert) {
return {
templateUrl: 'partials/component/uploadComponent.html',
restrict: 'A',
link: function(scope, element, attrs) {
element.closest("form")
.attr('enctype', 'multipart/form-data')
.attr('method', 'post')
.append("<input type='hidden' name='json'/>")
.submit(function() {
$("input[name='json']").val(angular.toJson(scope.model));
$(this).ajaxSubmit({
success: function(data) {
scope.$apply(function() {
scope.success(data);
});
}, error: function(data) {
scope.$apply(function() {
Alert.setErrors({
data: $.parseJSON(data.responseText)
});
});
}
});
return false;
});
},
scope: {
model: '=',
fileNameModel: '=',
success: '=',
label: '@'
}
};
}]);
<div ng-controller="ExampleController">
<form name="form" action="/rest/upload">
<div upload-component model="myModel" fileNameModel="myModel.name" success="onSuccess" label="attachment"></div>
</form>
</div>
'use strict';
app.controller('ExampleController', ['$scope', function($scope) {
$scope.myModel = {
exampleKey: "this will be submitted to the server, together with the file",
name: "blahblah.jpg"
};
$scope.onSuccess = function(data) {
console.log("form submitted");
console.dir(data);
}
}]);
<div class="control-group">
<label class="control-label capitalize" for="{{label}}">{{label}}:</label>
<div class="controls">
<input ng-hide="fileNameModel" type="file" name="file" />
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment