Skip to content

Instantly share code, notes, and snippets.

@OdeToCode
Last active December 14, 2015 03:59
Show Gist options
  • Save OdeToCode/5024867 to your computer and use it in GitHub Desktop.
Save OdeToCode/5024867 to your computer and use it in GitHub Desktop.
AngularJS Snippet
<div ng-app ng-controller="VideoController">
<table>
<thead>
<th>Title</th>
<th>Length</th>
<th></th>
</thead>
<tbody>
<tr ng-repeat="video in videos">
<td>{{video.Title}}</td>
<td>{{video.Length}}</td>
<td>
<button ng-click="editVideo(video.Id)">Edit</button>
<button ng-click="deleteVideo(video.Id)">Delete</button>
</td>
</tr>
</tbody>
</table>
<button ng-click="showEdit()">Create Video</button>
<div ng-show="isEditVisible">
<hr />
<form>
<input type="hidden" ng-model="editableVideo.Id" />
<label>Title:</label>
<input type="text" ng-model="editableVideo.Title" required />
<label>Length</label>
<input type="number" ng-model="editableVideo.Length" min="1" max="360" />
<input type="submit" value="Save" ng-click="saveVideo(editableVideo)" />
</form>
</div>
</div>
@section scripts{
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-resource.js"></script>
<script src="~/Scripts/underscore.js"></script>
<script>
var VideoController = function ($scope, $http) {
var serviceUrl = "/api/videos";
var blankVideo = {
Id: 0,
Title: "",
Length: 75
};
var videoFinder = function(id) {
return function(video) {
return video.Id == id;
};
};
var createVideo = function (newVideo) {
$http.post(serviceUrl, newVideo)
.success(function (video) {
$scope.videos.push(video);
});
};
var updateVideo = function(video) {
$http.put(serviceUrl + "/" + video.Id, video);
};
$scope.showEdit = function () {
$scope.isEditVisible = true;
$scope.editableVideo = angular.copy(blankVideo);
};
$scope.saveVideo = function (video) {
$scope.isEditVisible = false;
if (video.Id) {
updateVideo(video);
}
else {
createVideo(video);
}
};
$scope.editVideo = function (id) {
$scope.isEditVisible = true;
$scope.editableVideo = _.find($scope.videos, videoFinder(id));
};
$scope.deleteVideo = function (id) {
$http.delete(serviceUrl + "/" + id)
.success(function () {
$scope.videos = _.reject($scope.videos, videoFinder(id));
});
};
$scope.isEditVisible = false;
$http.get(serviceUrl).success(function (data) {
$scope.videos = data;
});
};
</script>
}
@dlidstrom
Copy link

Very nice example, thanks. Isn't line 57 missing a comma though?

@turnkey-commerce
Copy link

Good catch, it is missing a comma.

@herrherrmann
Copy link

… and line 57 is missing a comma, I think. It should be

var VideoController = function ($scope, Video) {         

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment