Created
May 29, 2013 11:22
-
-
Save wgroeneveld/5669593 to your computer and use it in GitHub Desktop.
angularjs jquery form plugin custom directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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: '@' | |
} | |
}; | |
}]); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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); | |
} | |
}]); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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