Skip to content

Instantly share code, notes, and snippets.

/app.js Secret

Created January 6, 2015 02:24
Show Gist options
  • Save anonymous/b5a9dd7634ee97bc01cf to your computer and use it in GitHub Desktop.
Save anonymous/b5a9dd7634ee97bc01cf to your computer and use it in GitHub Desktop.
Angular Service Question
angular.module('flapperNews', [])
.factory('postsFactory', [function(){
// Modularize posts frontend storage for better mock testing and independency of scope
var posts_factory_object = {
posts_list: []
};
return posts_factory_object;
}])
.controller('MainCtrl', [
'$scope',
'postsFactory',
function($scope, postsFactory){
// Bind scope.posts to postsFactory.posts_list
$scope.posts = postsFactory.posts_list;
// Variable pseudo post data for test
$scope.posts = [
{title: 'post 1', upvotes: 5},
];
// Frontend function for keeping track of state purely in frontend
$scope.addPost = function(){
// Check if inputted string is undefinied or empty
if (!$scope.title || $scope.title ===''){ return; }
$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: 0
});
$scope.title = '';
$scope.link = '';
console.log(postsFactory.posts_list);
console.log($scope.posts);
};
}]);
<form ng-submit="addPost()"
style="margin-top:30px;">
<h3>Add a new post</h3>
<div class="form-group">
<!--Store text input into title variable in MainCtrl scope-->
<input type="text"
class="form-control"
placeholder="Title"
ng-model="title"></input>
</div>
<div class="form-group">
<!--Store text into $scope.link-->
<input type="text"
class="form-control"
placeholder="Link"
ng-model="link"></input>
</div>
<button type="submit">Post</button>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment