Saturday, August 25, 2012

Is AngularJS very easy that there are very few blogs documenting it?

This app demonstrates how easy it is to structure your model with AngularJS and the UI automatically follow what happens to model seamlessly.

Live demo: http://jsfiddle.net/bpvjL/6/


HTML:

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="TodoCtrl">


    <ul class="unstyled">
      <li ng-repeat="todo in todos" >       
          <span class="isactive-{{activeTodo == todo}}" ng-click="changeActive(todo)" >
              <a href="#" style="none">{{todo.text}}</a>
          </span>
      </li>
    </ul>
      
      

    <form ng-submit="addTodo()">
      <input type="text" ng-model="todoText"  size="30"
             placeholder="add new todo here">
      <input class="btn-primary" type="submit" value="add">
    </form>
          
      <ul>
      <li ng-repeat="step in activeTodo.steps">
          {{$index + 1}} {{step.text}}
      </li>   
      </ul>

    <form ng-submit="addStep()">
      <input type="text" ng-model="stepText"  size="30"
             placeholder="add new step to: {{activeTodo.text}}">
      <input class="btn-primary" type="submit" value="add">
    </form>
          
  </div>
</div>
​


Javascript:

function TodoCtrl($scope) {
  $scope.todos = [
    {text:'learn angular',
     steps : [
         { text : 'learn' },
         { text : 'to' },           
         { text : 'build' }                    
     ]},
    {text:'build an angular app',
     steps : [ 
         { text : 'build' },         
         { text : 'and' }, 
         { text : 'they' }, 
         { text : 'will' }, 
         { text : 'come' }
     ]}
  ];
    
  $scope.activeTodo = $scope.todos[0];
  

  $scope.addTodo = function() {
        var todo = {text:$scope.todoText, steps: []};
        $scope.todos.push(todo);
        $scope.todoText = '';
        $scope.activeTodo = todo;
  };
    
  $scope.changeActive = function(active) {
        $scope.activeTodo = active;
  };


  $scope.addStep = function() {
        $scope.activeTodo.steps.push({text:$scope.stepText});
        $scope.stepText = '';
  };
    

}

​


CSS:

<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
<style>
.isactive-true {
    background: YELLOW;
}

No comments:

Post a Comment