Monday, May 4, 2015

JQuery UI with AngularJS Directive, Datepicker, migration to AngularJS new version

henriquat.re  is an interesting project on AngularJS from the .net developer’s point of view. Their article  on  Combining AngularJS with existing Components gives an elegant approach to combine JQuery UI datepicker fragment and move it to a reusable AngularJS directive.
When I tried the code with the latest AngularJS and JQuery UI releases the code did not work. I researched and found the problem. As stated in AngularJS Migrating from Previous Versions 
“Due to 3f2232b5, $controller will no longer look for controllers on window. The old behavior of looking on window for controllers was originally intended for use in examples, demos, and toy apps. We found that allowing global controller functions encouraged poor practices, so we resolved to disable this behavior by default.
To migrate, register your controllers with modules rather than exposing them as globals:”
I also used the idea given in Stackflow question  Adding directive makes controller undefined in angular js code  answered by James Allardice.
My modified code is given below
HTML index.html
 <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<!--
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
-->
<!-- Embedded Fragment - maindiv -->
<div ng-app="demo" ng-controller="DemoController">
    Date Of Birth:
    <my-datepicker type="text" ng-model="user.dateOfBirth" />
    <br>
    Current user's date of birth:
    <span id="dateOfBirthDisplay">{{user.dateOfBirth}}</span>
</div>
<!-- Fragment End - maindiv -->

<!--<script src="angular.js"></script>-->
<!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>-->
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js"></script>

<script src="demo.js"></script>
<link rel="stylesheet" href="demo.css">
 
JavaScript 
demo.js
/* Embedded Fragment - controller */
//function DemoController($scope) {
//   $scope.user = {
//      dateOfBirth: new Date(1970, 0, 1)
//   }
//}
//
var demo = angular.module("demo", []);
//
demo.controller("DemoController",  function($scope) {

   $scope.user = {
      dateOfBirth: new Date(1970, 0, 1)
       
   }
});
/* Fragment End - controller */

/* Embedded Fragment - directive */

demo.directive('myDatepicker', function ($parse) {
   return {
      restrict: "E",
      replace: true,
      transclude: false,
      compile: function (element, attrs) {
         var modelAccessor = $parse(attrs.ngModel);

         var html = "<input type='text' id='" + attrs.id + "' >" +
            "</input>";

         var newElem = $(html);
         element.replaceWith(newElem);

         return function (scope, element, attrs, controller) {

            var processChange = function () {
               var date = new Date(element.datepicker("getDate"));

               scope.$apply(function (scope) {
                  // Change bound variable
                  modelAccessor.assign(scope, date);
               });
            };

            element.datepicker({
               inline: true,
               onClose: processChange,
               onSelect: processChange
            });

            scope.$watch(modelAccessor, function (val) {
               var date = new Date(val);
               element.datepicker("setDate", date);
            });

         };

      }
   };
});

/* Fragment End - directive */

References
  1. henriquat.re 
  2. Combining AngularJS with existing Components
  3. AngularJS Migrating from Previous Versions 
  4. Adding directive makes controller undefined in angular js code
  5. AngularJS versions

Sunday, April 20, 2014

Syntax for accessing Json objects with “–” orspace in key

I  recently had to access Json object returned by Wikipedia with a key  name “query-continue”.

This can be done by using   ECMAscripts "bracket notation" 

response.data['query-continue'].categorymembers.gcmcontinue

refer

access javascript object with space in key

Thursday, April 17, 2014

angularjs page slider

Needed a sliding panel like the ones in Ipad for cascading dropdown. I wanted a button to open the dropdown panel and the panel to close after the last dropdown finished.

I used the nice directive provided by

Daniele Piccone in ng-pageslide

I have given below some code snippets to achieve this using the ng-pageslide directive.

<a  class="btn btn-primary"  ng-click="drop_down_open=true">Open</a>

<pageslide ps-open="drop_down_open" pageslide="left" ps-size="550px" ps-speed="0.5" ps-target="#div_dropdown"></pageslide>

<div id="div_dropdown">

<a ng-click="drop_down_open=false" class="btn btn-primary" >Close</a>
<div data-ng-include data-src="'pages/dropdown.html'">
</div>



In the controller to close or open



$scope.drop_down_open=false;

$scope.drop_down_open=true;

Saturday, March 15, 2014

Angulajs, Nodejs, Node-webkit articles coming

Have been busy with other projects.
Angularjs, Nodejs, Node-webkit are very exciting developments which happened in the last few years.
Some of the applications I did with Silverlight will be lot simpler with these.
Look for more articles about these technologies here.
 

Friday, September 28, 2012

Jquery cross domain AJAX requests and HTML parsing list of image src using JQUERY MAP

Recently I have been working with Wikipedia, Wikimedia and had to do AJAX requests and parsing the returned HTML.

Javascript and JQUERY have problems when you try an AJAX query to cross-domain sites. I read the following article by Micahs

Making Cross Domain jQuery AJAX Calls and followed the method suggested using YQL and seems to work fine. I have repeated below the code mentioned in the article for reference.

//feel free to add querystring vars to this
var myurl="http://www.example.com/get-post.ashx?var1=var1value&callback=?";
//make the call to YQL
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(myurl)+
"%22&format=xml'&callback=?",
function(data){
if(data.results[0]){
//this data.results[0] is the return object you work with,
//if you actually want to do something with the returned json
alert(data.results[0]);
} else {
var errormsg = '
Error: could not load the page.
'
;
//output to firebug's console
//use alert() for other browsers/setups
console.log(errormsg);
}
}
);



I have given below an example of parsing all the image source in a list of images.



The list item code snippet is given below



    <div class="thumb" style="width: 150px;"><div style="margin:15px auto;"><a href="//commons.wikimedia.org/wiki/File:Adrien_Ysenbrandt_-_Virgin_and_Child_with_Two_Angels_in_a_Landscape_-_Walters_37266.jpg" class="image"><img alt="Adrien Ysenbrandt - Virgin and Child with Two Angels in a Landscape - Walters 37266.jpg" src="//upload.wikimedia.org/wikipedia/commons/thumb/4/49/Adrien_Ysenbrandt_-_Virgin_and_Child_with_Two_Angels_in_a_Landscape_-_Walters_37266.jpg/102px-Adrien_Ysenbrandt_-_Virgin_and_Child_with_Two_Angels_in_a_Landscape_-_Walters_37266.jpg" width="102" height="120" /></a></div></div>


After alert(data.results[0]); you can do something like the following to get the  thumb html in the list:



 var thumb_array_img = $(('.thumb img'), result);


To get all the src links in an array use the JQUERY map function like the following code:



image_thumb_array = [];


image_thumb_array = $(thumb_array_img).map(function ()

                   { return $(this).attr("src"); });

Wikimedia Wikipedia parsing data and machine readable code useful links

The Wikipedia, Wikimedia API has lot of information but not well documented. I have been working with that to get some data and parse it. I found the following links very helpful.

  1. API:Main page
  2. MediaWiki API documentation page
  3. API sandbox
  4. Commons:Machine-readable data
  5. Category:Infobox templates
  6. What is the Full URL of the images returned by a wikipedia query...
  7. API:Query
  8. Call Wikipedia API using jQuery
  9. Manual:Parameters to index.php
  10. Template:Information
  11. API:Properties
  12. API:Lists

Wikipedida Wikimedia query returns 403 forbidden

I had the following webclient request 
 WebClient serviceRequest = new WebClient();
var JsonResponse = serviceRequest.DownloadString(new Uri(urselected));

Where urselected was the REST query string. The query worked fine in my browser but returned 403 forbidden error. I found the following post which addresses the problem:

Wikipedia query returns error 403

Modified my code as follows and it worked find:

WebClient serviceRequest = new WebClient();
           serviceRequest.Headers.Add("user-agent", "Silver Azure");

           var JsonResponse = serviceRequest.DownloadString(new Uri(urselected));