Tuesday, August 19, 2014

AngularJS: paging

There should be better way to do the paging for AngularJS. However this is my version of paging, and it works.
<div id='xxxPaging' ng-show="getPageTotal().length > 1">
     <span ng-class="{spanLink:!hover,spanLinkhover:hover}" ng-mouseover="hover=true" ng-mouseleave="hover = false" ng-click="searchCall('paging',current-1);"  ng-show="1!=current && getPageTotal().length>3"><</span>
       <span ng-repeat="i in getPageTotal() track by $index">

         <b ng-show="i==current" class="spanNoLink">{{i}}</b>     

         <span ng-class="{spanLink:!hover,spanLinkhover:hover}" ng-mouseover="hover=true" ng-mouseleave="hover = false" ng-click="searchCall('paging',i);"  ng-show="i!=current && (i-1 == current || i - 2 == current || i + 1  == current || i + 2 == current || i == 1 || i == getPageTotal().length)">{{i}}</span>

         <span class="spanNoLink" ng-show="i != current && i < getPageTotal().length && (i+ 3 == current || i- 3 == current ) && i+3 != 4">..</span>

      </span>
      <span ng-class="{spanLink:!hover__,spanLinkhover:hover__}" ng-mouseover="hover__=true" ng-mouseleave="hover__ = false" ng-click="searchCall('paging',current+1);"  ng-show="getPageTotal().length!=current && getPageTotal().length>3">></span>
</div>

Sunday, August 17, 2014

JSON string as stored proc parameter

Thanks to the article converts a JSON string into a table, I am able to send JSON directly to Stored Proc as input param:



ALTER PROCEDURE [XXXXXX].[xxx_xxx_xxxxxxx]
@SearchCriteria NVARCHAR(max)

AS


---------------------------
-- EF use for Dynamic SQL
---------------------------
IF ( @SearchCriteria IS NULL )
BEGIN
      SELECT
          CAST(NULL AS NVARCHAR(5) ) AS Category,
            CAST(NULL AS NVARCHAR(100)) AS FinancialInstitution,
            CAST(NULL AS NVARCHAR(50)) AS CompanyType,
            CAST(NULL AS NVARCHAR(10)) AS Redeemable,
            CAST(NULL AS NVARCHAR(10)) AS CompoundFreq,
            CAST(NULL AS NVARCHAR(10)) AS PaymentFreq,
            CAST(NULL AS DECIMAL(12,2)) AS MinAmount,
            CAST(NULL AS DECIMAL(12,2) ) AS MaxAmount,
            CAST(NULL AS DECIMAL(5,2)) AS TERM,
            CAST(NULL AS DECIMAL(8,4) ) AS Rate
END

BEGIN



DECLARE @termVal DECIMAL(5,2);
DECLARE @termDY NVARCHAR(300);
DECLARE @termDYSelectedTogether NVARCHAR(400) = '';
--TermTarget
DECLARE @termTarget NVARCHAR(5) = '';

DECLARE @minDeposit NVARCHAR(200);
DECLARE @minDepositSelectedTogether NVARCHAR(260) = '';




DECLARE @interestRate DECIMAL(8,4);
DECLARE @companySelected NVARCHAR(max) ;
DECLARE @companySelectedTogether NVARCHAR(max) = '';

DECLARE @companyTypeSelected NVARCHAR(max) ;
DECLARE @companyTypeSelectedTogether NVARCHAR(max) = '';

DECLARE @redeemSelected NVARCHAR(25) ;
DECLARE @redeemSelectedTogether NVARCHAR(25) = '';

DECLARE @taxIndicatorSelected NVARCHAR(25) ;
DECLARE @taxIndicatorSelectedTogether NVARCHAR(25) = '';

DECLARE @compoundFreqSelected NVARCHAR(50) ;
DECLARE @compoundFreqSelectedTogether NVARCHAR(50) = '';
DECLARE @PaymtFreqSelected NVARCHAR(80) ;
DECLARE @PaymtFreqSelectedTogether NVARCHAR(80) = '';
DECLARE @tbl TABLE
( id int, name NVARCHAR(255), value NVARCHAR(max),  errcnt int,msg varchar(8000)
);

INSERT INTO
      @tbl
SELECT
      id,
      name,
      value,
      errcnt,
      msg
FROM
      dbo.fn_SplitJson2(@SearchCriteria,null);


------------------------------
--Term
------------------------------

SELECT
      @termTarget = value
FROM
      @tbl
WHERE
      name = 'TermTarget'

IF @termTarget <> ''
BEGIN
      SELECT
            @termVal = value
      FROM
            @tbl
      WHERE
            name = 'Months'
END
ELSE
BEGIN
      SELECT
            @termDY = value
      FROM
            @tbl
      WHERE
            name = 'Months'


      --@termDYSelectedTogether
      IF @termDY <> 'ALL'
      BEGIN
      IF @termDY <> ''
        BEGIN
                  SELECT
                  @termDYSelectedTogether=
                     CASE WHEN COALESCE(@termDYSelectedTogether,'')=''
                        THEN  QUOTENAME(value,'''')
                        ELSE  @termDYSelectedTogether+',' + QUOTENAME(value,'''')
                     END
                  FROM
                  dbo.fn_SplitJson2(
                  @termDY,NULL
                  )
        END
        ELSE
         BEGIN
            SELECT @termDYSelectedTogether= ''
         END
      END

END
------------------------------
--Deposit
------------------------------
SELECT
      @minDeposit = value
FROM
      @tbl
WHERE
      name = 'Deposit'


IF @minDeposit <> 'ALL'
BEGIN
IF @minDeposit <> ''
  BEGIN
            SELECT
            @minDepositSelectedTogether=
               CASE WHEN COALESCE(@minDepositSelectedTogether,'')=''
                  THEN  QUOTENAME(value,'''')
                  ELSE  @minDepositSelectedTogether+',' + QUOTENAME(value,'''')
               END
            FROM
            dbo.fn_SplitJson2(
            @minDeposit,NULL
            )
  END
  ELSE
   BEGIN
      SELECT @minDepositSelectedTogether= ''
   END
END



------------------------------
--Rate
------------------------------
SELECT
      @interestRate = value
FROM
      @tbl
WHERE
      name = 'Rate'

.......
.......

Wednesday, August 13, 2014

IE 11 navigator.userAgent has no MSIE

if( navigator.userAgent.toLowerCase().indexOf('firefox') > 0 ){

     $('#GICCriteriaRate span.rateSelect').each(function (i, ob) {

    $(ob).switchClass( 'rateSelect', 'rateSelectMoz' );

   });
  }else if( navigator.userAgent.toUpperCase().indexOf('MSIE') > 0 || 
            !!navigator.userAgent.match(/Trident.*rv[ :]*11\./) ||  
      !!navigator.userAgent.match(/Trident.*rv[ :]*12\./)){

     $('#GICCriteriaRate span.rateSelect').each(function (i, ob) {

    $(ob).switchClass( 'rateSelect', 'rateSelectIE' );

   });

  }

The !! construct is a simple way of converting any JS expression into its Boolean equivalent, just the logical NOT operator, twice. For example: !!"ANGULAR JS" === true and !!0 === false. Here we end up converting a function(string's match()) into its Boolean equivalent.
!! simulates the behavior of the Boolean() casting function. The end result is the same as using the Boolean() function on a value.

Tuesday, August 12, 2014

ANGULARJS: sorting direction up/down using css

.caret {
    border: 5px solid transparent;
    display: inline-block;
    width: 0;
    height: 0;
    opacity: 1;
    color:
    vertical-align: top;
}

.caret.up {
    border-bottom: 5px solid #fff;
}

.caret.right {
    border-left: 5px solid #fff;
}

.caret.down {
    border-top: 5px solid #fff;
}

.caret.left {
    border-right: 5px solid #fff;
}

<span class='caret' ng-class="{down:sortingTarget==m.Id&& sortingDirection,up:sortingTarget==m.Id&& !sortingDirection}"></span>

Friday, August 8, 2014

AngularJS: css Class Change on mouseover

It is as easy as below in AngularJS:


<span ng-class="{headSpanLink:!hover,headSpanLinkhover:hover}" ng-mouseover="hover=true" ng-mouseleave="hover = false">Check all</span>


OR


<span ng-class="{hover:hover}" ng-mouseover="hover=true" ng-mouseleave="hover = false">Uncheck all</span>

AngularJS: $element injecting into controller not for Routing

$element can be injected into controller in normal cases but not in routing

I got the explanlation from here:

 your "typical" controller in fact IS a directive controller! So the injectable locals just happen to be available to any controller using ngController. But it's NOT available using a route because ngView uses a more "normal" controller instantiation


It throws error like this if you try in routing ( in the routing controller ):


Error: [$injector:unpr] http://errors.angularjs.org/1.2.15/$injector/unpr?p0=%24elementProvider%20%3C-%20%24element
    at Error (native)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:6:450
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:34:510
    at Object.c [as get] (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:33:83)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:35:59
    at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:33:83)
    at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:33:300)
    at Object.instantiate (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:33:464)
    at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:65:486)
    at link (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular-route.js:913:26) <div ng-view="" class="ng-scope"> 


Wednesday, August 6, 2014

AngularJS: Render HTML tags in a string

Even HTML escape renders as text string not html without $sce.trustAsHtml in AngularJS.

Reason:
The interpolation directive will do the escaping of any HTML content found in the model in order to prevent HTML injection attacks.


Here is what I got:

<span class="headSpanLink" ng-click="searchCall(m.Id,-1)" ng-bind-html='transform(m.Disc)'></span>




    $scope.transform =function(n){      
   if( n!='undefined' ){
        var t = $sce.trustAsHtml(n.split(' ').join("<br>"));
        console.log(t);
        return t;
         
        }
 }

Saturday, August 2, 2014

AngularJS: $http service call being moved to factory as well as $q promise

The Service
xxxApp.factory('myService', function(($q, $timeout, $http){
    return {

        //$http post
        method1: function() {
            return $http.post('/services', { 
                type : 'getSource',
                ID    : 'TP001'
            });
        },

        //$q promise
        method2: function() {
           var deferred = $q.defer();
      
           $timeout(function() {
             deferred.resolve('This is result 2!');
           }, 2000);
      
            return deferred.promise;
        },

        //$http get
        method3: function() {
           return $http.get('stuff');
        },

       //$http returns a promise, which has a then function, which also returns a promise
       async: function() {    
           var promise = $http.get('test.json').then(function(response) {
            // The then function here is an opportunity to modify the response
            console.log(response);
            //The return value gets picked up by the then in the controller.
            return response.data;
           });
        // Return the promise to the controller
        return promise;
        }
    };
});




The Controller

xxxApp.controller('myCtrl',function($scope, myService){
    $scope.result1 = [];

    var handleSuccess = function(data, status) {
        $scope.result1 = data;
        console.log($scope.result1);
    };

    myService.method1().success(handleSuccess);

    $scope.result2 = myService.method2();
    $scope.result3 = myService.method3();


    // Call the async method and then do stuff with what is returned inside our own then function
    myService.async().then(function(d) {
    $scope.data = d;
    });

});


And the view part:

<html ng-app="myApp" ng-controller="myCtrl">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2/angular.min.js"></script>
<meta charset=utf-8 />
<title>Factory $q promise etc.</title>
</head>
<body>
  <div ng-show="!result1">Waiting...</div>
  <div>{{result1}}</div>
  <hr>
  <div ng-show="!result2">Waiting...</div>
  <div>{{result2}}</div>
  <hr>
  <div ng-show="!result3">Waiting...</div>
  <div>{{result3}}</div>
</body>
</html>

Friday, August 1, 2014

AngularJS: $watch is very useful to defer the template showing, together with JQuery

When I have 2 controllers being called and one controller's post parameters rely on the first controller's data fetched from server, I need to hide the template being used by the 2nd controller (before it fully loaded to the browser). It took me a while to find the right solution. And here is the one I consider comfortable, using $watch

1. create a directive with $watch to keep checking
xxxXXXApp.directive("ngDivload", function () {
    return function (scope, element, attrs) {
        scope.$watch("xxxResultModel.Header", function (obj) {
            var value = obj || null;            
            if (value){
                    $('.tgXXX .searchCount').show();
                    $('.searchResult').show();
            }
                
        });
    };
});
xxxResultModel.Header is the $scope object being assigned at the end of the 2nd controller operation

2. Add this directive to the template for the 2nd controller

<div ng-cloak class="ng-cloak searchResult" ng-Divload="" style="display:none;">