Start a series of posts how to code apps. First ever app with AngularJS and Yii was very simple. We'll talk about a few topics. Demos find here Simple Single Page app with a table of users - u can browse, edit, delete, see details - without reloading the page ;) Folder with all oof the front (AngularJS files) looked like this (In images folder glyphicons.png files located):

Pix with folders

First, create a view like that:

<?php
//task.php
$url = Yii::app()->request->baseUrl;
     echo '<div ng-app="ngdemoApp">
      <ul class="menu">
        <li><a href="#/dummy">dummy</a></li>
        <li><a href="#/user-list">user-list</a></li>
        <li><a href="#/user-detail/1">user-detail/1</a></li>
        <li><a href="#/user-creation">user-creation</a></li>
      </ul>
 
      <div class="container" ng-view=""></div>
      <script src="'.$url.'/front/tableUser/scripts/app.js"></script>
      <script src="'.$url.'/front/tableUser/scripts/services/services.js"></script>
      <script src="'.$url.'/front/tableUser/scripts/controllers/controllers.js"></script>
 
    </div>';
 
    ?>

In VIEWS folder 4 views located:

<!--dummy.html-->
<div>
    <p>
        Result from Angular Controller is: {{ bla }}
    </p>
    <p>
        Result from REST Web Service is: {{ foo }}
    </p>
    <p>
      The result from REST Web Service should be: <b>JonFromREST</b>
    </p>
    <p>
      If the result from REST Web Service is empty: Check that the backend REST Web Service is running and returning the expected result.
    </p>
    <ol>
      <li>in modern browsers just open a new tab and enter <i>http://localhost:8080/ngdemo/web/dummy</i> <b>or</b></li>
      <li>run the script <i>../test_backend.sh</i>, <b>or</b></li>
      <li>execute curl directly from the command line:<i>curl -i -X GET -H 'Content-Type: application/json' http://localhost:8080/ngdemo/web/dummy </i><b>or</b></li>
    </ol>
    <p>Maybe you just forgot to start the backend REST Web Service? <i>../start_backend_java_backend.sh</i></p>
    All of the above results should contain:
    <div>
      <b>{"id":0,"firstName":"JonFromREST","lastName":"DoeFromREST"}</b>
    </div>
</div>
 
<!--user-detail.html-->
<div class="container">
  <h1>User detail</h1>
 
  <form novalidate="novalidate" class="form-horizontal">
    <div class="control-group">
      <label class="control-label" for="inputFirstName">First name:</label>
 
      <div class="controls">
        <input type="text" id="inputFirstName" ng-model="user.firstName"/>
      </div>
    </div>
    <div class="control-group">
      <label class="control-label" for="inputLastName">Last name:</label>
 
      <div class="controls">
        <input type="text" id="inputLastName" ng-model="user.lastName"/>
      </div>
    </div>
    <div class="control-group">
      <div class="controls">
        <a ng-click="cancel()" class="btn btn-small">cancel</a>
        <a ng-click="updateUser()" class="btn btn-small btn-primary">update user</a>
      </div>
    </div>
  </form>
</div>
 
<!--user-creation.html-->
<div class="container">
  <h1>Create a new user</h1>
 
  <form novalidate="novalidate" class="form-horizontal">
    <div class="control-group">
      <label class="control-label" for="inputFirstName">First name:</label>
 
      <div class="controls">
        <input type="text" id="inputFirstName" ng-model="user.firstName" placeholder="First name"/>
      </div>
    </div>
    <div class="control-group">
      <label class="control-label" for="inputLastName">Last name:</label>
 
      <div class="controls">
        <input type="text" id="inputLastName" ng-model="user.lastName" placeholder="Last name"/>
      </div>
    </div>
    <div class="control-group">
      <label class="control-label" for="inputPass">Password:</label>
 
      <div class="controls">
        <input type="text" id="inputPass" ng-model="user.pass" placeholder="password"/>
      </div>
    </div>
    <div class="control-group">
      <div class="controls">
        <a ng-click="createNewUser()" class="btn btn-small btn-primary">create new user</a>
      </div>
    </div>
  </form>
</div>
 
<!--user-list.html-->
<div class="span6">
  <table class="table table-striped table-condensed">
    <thead>
      <tr>
        <th style="min-width: 80px;">First name</th>
        <th style="min-width: 80px;">Last name</th>
        <th style="width:20px;">&nbsp;</th>
        <th style="width:20px;">&nbsp;</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="user in users">
        <td>{{ user.firstName }}</td>
        <td>{{ user.lastName }}</td>
        <td><a ng-click="editUser(user.id)" class="btn btn-small btn-primary">edit</a></td>
        <td><a ng-click="deleteUser(user.id)" class="btn btn-small btn-danger">delete</a></td>
      </tr>
    </tbody>
  </table>
  <a ng-click="createNewUser()" class="btn btn-small">create new user</a>
</div>

In SCRIPTS folder we got 3 js files:

//app.js - main file - ROUTES defined
'use strict';
 
angular.module('ngdemoApp', [
  'ngRoute',
  'ngdemoApp.services',
  'ngdemoApp.controllers'
  ])
.config(function ($routeProvider, $httpProvider) {
    var baseUrl = "http://localhost:8084/yiiangular/";
  $routeProvider.when('/dummy', {templateUrl: baseUrl + 'front/tableUser/views/dummy.html', controller: 'DummyCtrl'});
  $routeProvider.when('/user-list', {templateUrl: baseUrl + 'front/tableUser/views/user-list.html', controller: 'UserListCtrl'});
  $routeProvider.when('/user-detail/:id', {templateUrl: baseUrl + 'front/tableUser/views/user-detail.html', controller: 'UserDetailCtrl'});
  $routeProvider.when('/user-creation', {templateUrl: baseUrl + 'front/tableUser/views/user-creation.html', controller: 'UserCreationCtrl'});
  $routeProvider.otherwise({redirectTo: '/user-list'});
 
  /* CORS... */
  /* http://stackoverflow.com/questions/17289195/angularjs-post-data-to-external-rest-api */
  $httpProvider.defaults.useXDomain = true;
  delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
 
//controllers.js
'use strict';
 
/* Controllers */
 
var app = angular.module('ngdemoApp.controllers', []);
 
 
// Clear browser cache (in development mode)
//
// http://stackoverflow.com/questions/14718826/angularjs-disable-partial-caching-on-dev-machine
app.run(function ($rootScope, $templateCache) {
  $rootScope.$on('$viewContentLoaded', function () {
    $templateCache.removeAll();
  });
});
 
 
app.controller('DummyCtrl', ['$scope', 'DummyFactory', function ($scope, DummyFactory) {
  $scope.bla = 'тестируем отдачу кириллицй';
  DummyFactory.query({}, function (data) {
    $scope.foo = data.firstName;
  })
}]);
 
app.controller('UserListCtrl', ['$scope', 'UsersFactory', 'UserFactory', '$location',
  function ($scope, UsersFactory, UserFactory, $location) {
 
    /* callback for ng-click 'editUser': */
    $scope.editUser = function (userId) {
      $location.path('/user-detail/' + userId);
    };
 
    /* callback for ng-click 'deleteUser': */
    $scope.deleteUser = function (userId) {
      UserFactory.delete({ id: userId });
      $scope.users = UsersFactory.query();
    };
 
    /* callback for ng-click 'createUser': */
    $scope.createNewUser = function () {
      $location.path('/user-creation');
    };
 
 
    $scope.users = UsersFactory.query();
    var usersList  = UsersFactory.query();
  }]);
 
app.controller('UserDetailCtrl', ['$scope', '$routeParams', 'UserFactory', '$location',
  function ($scope, $routeParams, UserFactory, $location) {
 
    /* callback for ng-click 'updateUser': */
    $scope.updateUser = function () {
      UserFactory.update($scope.user);
      $location.path('/user-list');
    };
 
    /* callback for ng-click 'cancel': */
    $scope.cancel = function () {
      $location.path('/user-list');
    };
 
    $scope.user = UserFactory.show({id: $routeParams.id});
  }]);
 
app.controller('UserCreationCtrl', ['$scope', 'UsersFactory', '$location',
  function ($scope, UsersFactory, $location) {
 
    /* callback for ng-click 'createNewUser': */
    $scope.createNewUser = function () {
      UsersFactory.create($scope.user);
      $location.path('/user-list');
    }
  }]);
 
//services.js - FACTORY defined
'use strict';
 
var services = angular.module('ngdemoApp.services', ['ngResource']);
 
//var baseUrl = 'http://localhost:8084/yiiangular/index.php';
var baseUrl = "http://localhost:8084/yiiangular/index.php/api/";
 
services.factory('DummyFactory', function ($resource) {
    return $resource('../views/dummy',
 
                     {},
                      {
        query: { method: 'GET', params: {} }
    })
});
 
services.factory('UsersFactory', function ($resource) {
    //return $resource(baseUrl + 'user',
    var usersList = $resource(baseUrl + 'user',
                     {}, {
        query: { method: 'GET', isArray: true },
        create: { method: 'POST' }
    });
     var usersList2 = usersList.query(function() {});
    return usersList;
 
});
 
services.factory('UserFactory', function ($resource) {
    return $resource(baseUrl + 'user/:id',
 
                     {}, {
        show: { method: 'GET' },
        update: { method: 'PUT', params: {id: '@id'} },
        delete: { method: 'DELETE', params: {id: '@id'} }
    })
});

Leave a Comment

Fields with * are required.

Please enter the letters as they are shown in the image above.
Letters are not case-sensitive.