giovedì 19 marzo 2015

How to implement the click TAB event in a TAB Panel controller, with HTML and AngularJS.

AngularJS v. 1.2.14, Bootstrap v3.3.1

In my web page, I have this HTML code that defines a tab panel control like this:

<div ng-controller="PanelController as panelCtrl">
       <ul class="nav nav-tabs">
             <li ng-class="{ active:panelCtrl.isSelected(1)}">
                    <a ng-click="panelCtrl.selectTab(1)">Tab 1</a>
             </li>
             <li ng-class="{ active:panelCtrl.isSelected(2)}">
                    <a ng-click="panelCtrl.selectTab(2)">Tab 2</a>
             </li>
             <li ng-class="{ active:panelCtrl.isSelected(3)}">
                    <a ng-click="panelCtrl.selectTab(3)">Tab 3</a>
             </li>
       </ul>
       <div class="tab-content">
             <div class="panel" ng-show="panelCtrl.isSelected(1)">
                    <div>
                           <br />
                    </div>
             </div>
             <div class="panel" ng-show="panelCtrl.isSelected(2)">
                    <div>
                           <br />
                    </div>
             </div>
             <div class="panel" ng-show="panelCtrl.isSelected(3)">
                    <div class="clearfix">
                           <br />
                    </div>
             </div>
       </div>
</div>

Then in my javascript module (app.js) there is the controller “PanelController” definition:

(function() {
       angular.module('app', [
                    'ui.bootstrap'
             ])          
             .controller('PanelController', ['$scope', function ($scope) {
                    var self = this;

                    self.tab = 1;

                    self.selectTab = function(setTab) {
                           self.tab = setTab;
                    };

                    self.isSelected = function(checkTab) {
                           return self.tab === checkTab;
                    };

                    $scope.$on('defaultTab', function () {
                           self.tab =sharedPanelService.tab;
                    });                
             }])
})();

Well, now I want to implement an event when the user click on a TAB, for example the Tab 3 and for this purpose, I have added this factory:

.factory('sharedPanelService', function($rootScope) {
                    var sharedPanelService = {};

                    sharedPanelService.prepForBroadcastClickItem = function (tab) {
                           this.tab = tab;
                           this.broadcastClickItem();
                    };                 

                    sharedPanelService.broadcastClickItem = function () {
                           $rootScope.$broadcast('clickTab');
                    };

                    return sharedPanelService;
             })

and I have modified the “PanelController” in this way, adding this statement
sharedPanelService.prepForBroadcastClickItem(setTab);


 The new “PanelController” is:

.controller('PanelController', ['$scope', 'sharedPanelService', function ($scope, sharedPanelService) {
                    var self = this;

                    self.tab = 1;

                    self.selectTab = function(setTab) {
                           self.tab = setTab;
sharedPanelService.prepForBroadcastClickItem(setTab);
                    };

                    self.isSelected = function(checkTab) {
                           return self.tab === checkTab;
                    };

                    $scope.$on('defaultTab', function () {
                           self.tab =sharedPanelService.tab;
                    });                
             }])

where I have injected the sharedPanelService

Finally in the javascript module (customer.js) where I want to intercept the click event I have injected the sharedPanelService and modified the code like this:

(function() {

       angular.module('customer', ['ui.bootstrap'])
             .controller('CustomerController', [
                    '$scope', 'sharedPanelService',
                    function($scope, sharedPanelService) {

                           $scope.$on('clickTab', function() {
                                  var tabSelected = sharedPanelService.tab;

                                  // If Tab 3.
                                  if (tabSelected === 3) {
                                        // Todo something ...
                                  }
                           });
                    }
             ]);
})();



Kind regards!

lunedì 29 dicembre 2014

AngularJS (live-code)


Una giornata gratuita di LIVE CODING in cui gli speaker ti guideranno passo-passo all'utilizzo del framework Google AngularJS.

http://events.unshift.xyz/angular-js-07-feb-15/#/

martedì 25 novembre 2014

Input (HTML) validation calling a WEB API method (Part II)

AngularJS v. 1.2.14, WEB API (.NET Framework 4.51)

Based on my last post (http://diegoparolin-codeplus.blogspot.it/2014/10/input-html-validation-calling-web-api.html) I have added a custom Directive to my code, like this.

I first changed the javascript code, where I have created a custom Directive with inside the service that calls the WEB API. (factory).

(function() {
  var app = angular.module('verifyUser-registerUser', []);

  app.factory('checkFiscalCodeService', function ($q, $http) {
      var checkCode = function (value) {
        var deferred = $q.defer();

        $http({
          url: './Api/AccountAPI/CheckFiscalCode',
          method: 'GET',
          params: {
            fiscalCode: value
          }
        })
          .success(function (data) {
            deferred.resolve(data);
          })
          .error(function (reason) {
            deferred.reject(reason);
          });

        return deferred.promise;
      };
      return {
        CheckCode: function(value) {
          return checkCode(value);
        }
      };
    });

  app.directive('checkFiscalCode', ['checkFiscalCodeService', function (checkFiscalCodeService) {
      return {
        // restrict to an attribute type.
        restrict: 'A',

        // element must have ng-model attribute.
        require: 'ngModel',

        // scope = the parent scope
        // elem = the element the directive is on
        // attr = a dictionary of attributes on the element
        // ctrl = the controller for ngModel.
        link: function(scope, elem, attr, ctrl) {

          // add a parser that will process each time the value is
          // parsed into the model when the user updates it.
          ctrl.$parsers.unshift(function(value) {
            var valid = false;
            if (value != null && value.length === 16) {
              checkFiscalCodeService.CheckCode(value).then(function(response) {
                if (response === 'true') {
                  ctrl.$setValidity('validator', true);
                  valid = true;
                } else {
                  ctrl.$setValidity('validator', false);
                }
              }, function(errorResponse) {
                ctrl.$setValidity('validator', false);
              });
            } else {
              ctrl.$setValidity('validator', false);
            }
           
            return value;
          });

          // add a formatter that will process each time the value
          // is updated on the DOM element.
          ctrl.$formatters.unshift(function (value) {
            if (value != null && value.length === 16) {
              checkFiscalCodeService.CheckCode(value).then(function(response) {
                if (response === 'true') {
                  ctrl.$setValidity('validator', true);
                }
              }, function(errorResponse) {
                ctrl.$setValidity('validator', false);
              });
            }

            // return the value or nothing will be written to the DOM.
            return value;
          });
        }
      };
    }]);

  app.controller('RegisterUserController', [
    '$scope', '$http', function($scope, $http) {

    // Do something …

    }
  ]);   
})();

Therefore I have modified my html page in this way:

<div ng-controller="RegisterUserController as registerUser">
    <div class="form-container">
        <form name="form" class="form-horizontal" ng-submit="form.$valid && registerNewUser()" novalidate>
            <div class="row">
                <div class="col-md-7 col-md-offset-2">
<div class="form-group">
                        <label for="inputFiscalCode" class="col-md-4 control-label">Fiscal code</label>
                        <div class="col-md-8">
                            <input name="inputFiscalCode" type="text" class="form-control" id=" inputFiscalCode " ng-model="fiscalCode"
                                   required placeholder="Fiscal code" check-fiscal-code
                                   ng-class="{true: 'ng-invalid ng-dirty'}[submitted]">
                            <span ng-show='form.inputFiscalCode.$error.validator && form. inputFiscalCode.$dirty'>Fiscal code is not valid!</span>
                        </div>
                    </div>
<div class="form-group">
                        <div class="col-md-offset-6 col-md-4">
                            <button type="submit" class="btn btn-primary" ng-click="submitted=true">Register</button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

This is the same result:


Bye bye!