AngularjsActivitiesApp

From Education Centre
Jump to: navigation, search

Activities List

HTML Page

  • Set up your page with ng-app and the ng-controller
  • Links to CSS and AngularJs javascripts
  • Hide input field until activity edit button is clicked, in which case you show input field and hide text:
<body ng-app="sparta">
    <div class="container" ng-controller="CompetitionController">
        <div ng-repeat="activity in activities">
            <div ng-show="activity.isEdited">
                <input type="text" ng-model="activity.name"/> - <input type="text" ng-model="activity.points"/>
                <button ng-click="activity.isEdited = false">Ok</button>
            </div>
            <div ng-hide="activity.isEdited">
                {{activity.name}} - {{activity.points}} 
                <button ng-click="activity.isEdited = true">Edit</button>
                <button ng-click="removeActivity(activity)">Remove</button>
            </div>
        </div>      
    <div class="addNew">
        <button ng-click="addNewActivity()">Add New</button>
    </div>
    </div>
</body>


Javascript Code

  • Delcare you AngularJs module.
  • Define $scope variable and initialise with Json data.
  • Define your functions in the $scope.
  • addNewActivity() function and the editActivity() function and how to inline edit the two input fields and save the changes back into the array.
  • Use push() and pop() to add remove items from your list.
  • Use splice(index,number of items to remove) to change your list.



app = angular.module("sparta", []);

window.CompetitionController = function($scope) {

     $scope.activities = [{
        id: 6431,
        name: "Meeting",
        points: 20
    }, {
        id: 6432,
        name: "Deal",
        points: 100
    }];
    
    $scope.addNewActivity = function() {

        //This function should create 2 new input fields
        //The user should input the name and points
        //We can ignore the id for now
        //Then the object should be craeted and pushed in as you see below with the mock data.
        
        var updatedActivities = {
                id: 6433,
                name: "Call",
                points: 5
            };
    
            $scope.activities.push(updatedActivities);
    }
    
    $scope.editActivity = function(activity) {
        var selectedActivity = activity;
        console.log(selectedActivity);
    }
    
    $scope.removeActivity = function(activity) {
        activityId = activity.id; //the activity id

        var i = 0;
        for (var item in $scope.activities) {
            if ($scope.activities[item].id == activityId)
                break;
            i++;
        }

        $scope.activities.splice(i, 1);
    }
 
}


Code in JSFiddle

http://jsfiddle.net/A5xZ9/2/ Activities App code