Integrating the Bluemix Watson Translation service into an XPages application

In this article I will demonstrate how to integrate the Bluemix Watson Translation service into a functioning XPages application.

Bluemix Watson Translation Service

Following on from one from my previous posts on the subject I have been looking for a good workable example of using a Bluemix service within an XPages application. As I said before this is as much an exercise in me learning more about node.js and Bluemix as anything else – but I also love being able to share.

Based on the previous post about how to get the Watson Q and A service up and running it took me 12 minutes to get a working example of the Watson Translation service up and running on a Bluemix site. Just for disclaimers I have no idea how good the Watson service is and I am not advocating it – this is purely an exercise in being able to use a Bluemix service, more so that what it does.

So I followed the steps in my previous blog but applied them to the example post on the Watson Translation service. This was pretty simple and once again the only thing to change was the manifest.yml file to name the service and application correctly.

w2

http://xominowatsontranslate.mybluemix.net/

When you type into the TEXTAREA box (1) and then hit “Translate”(2) the result is displayed in the Output (3)

The page does a full refresh and the answer is displayed. The node.js code running behind the application is fairly self explanatory :

  • (looking at the code snippet below) we can see the values POST’d from the application are received on the node.js server in the app.POST
  • The posted field values are turned into a separate request to the Watson translation service
  • The Watson request (watson_req) is sent as a serversiude request to the Watson service
  • The results from that are sent back to the response object “watson_res”
  • The node.js response (res) back to the user is then set back to the browser using the jade template (index)
    • return res.render(‘index’,request_data);

// Handle the form POST containing the text and sid, reply with the language
app.post('/', function(req, res){

    var request_data = {
        'txt': req.body.text,
        'sid': req.body.sid,
        'rt':'text' // return type e.g. json, text or xml
    };

    var parts = url.parse(service_url);
    // create the request options to POST our question to Watson
    var options = { host: parts.hostname,
        port: parts.port,
        path: parts.pathname,
        method: 'POST',
        headers: {
            'Content-Type'  :'application/x-www-form-urlencoded', // only content type supported
            'X-synctimeout' : '30',
            'Authorization' :  auth }
    };

    // Create a request to POST to Watson
    var watson_req = https.request(options, function(result) {
        result.setEncoding('utf-8');
        var responseString = '';

        result.on("data", function(chunk) {
            responseString += chunk;
        });

        result.on('end', function() { //this is triggered when the response from Watson is completed
            // add the response to the request so we can show the text and the response in the template
            request_data.translation = responseString;
            console.log('request',request_data);
            return res.render('index',request_data); //<------response sent back to the web page
        })

    });

    watson_req.on('error', function(e) {
        return res.render('index', {'error': e.message})
    });

    // create the request to Watson
    watson_req.write(querystring.stringify(request_data));
    watson_req.end();

});

 

You can see that in action through firebug – here is the POST parameters

w3and here is the response – the new HTML containing the answer

w4

 

Modifying the service

Here is the thought process which occurred to me:

  • Well that is cool but if I want to integrate this into an XPage then I will need to return the result as JSON and not a whole HTML page
  • But I do not want to break the example so how can I do that ?
  • I can use a new route – so if I POST at a different URL, the node.js server can be made to be smart enough to do something different
  • Ah…….and then I will have CORS issues because my application will be running at xomino.com and the bluemix app is not

Replicating the POST as code

So the first thing I did was try and replicate the code in jQuery (as I know best) so that I could mimic a POST event in ajax without using a form. In the following example you can see I added jQuery to my page (jQuerify plugin for firebug). I then simulated an AJAX POST to the translation service (emulating the form post).

w5

 

The response is the HTML of the new page, so I know this is at least the right AJAX code.

w6

 

But when I am on the copper.xomino.com site and I try and repeat the same thing, as expected CORS issues.

w7

Ryan Baxter (who frankly has been a huge support and help in learning all this) said to me

“You are in luck, CORS is dead simple with Node  – https://www.npmjs.org/package/cors” and how right he was.

Adding the CORS package to my Bluemix application

The way you add a package to your Bluemix application is by updating the package.json file. This file contains all the npm modules that will be needed and what is even cooler is that these will be npm installed within your node server automagically on deployment

w8

So then I need to add the cors enabled page to my application. But I did not want to change the core example on the site. So what I did was create a new “route” within the node.js application and told it to do something different….

Originally we had this within the example


// Handle the form POST containing the text and sid, reply with the language
//the route in this case is "/" - so basically the root of the application
app.post('/', function(req, res){
	//stuff
}

and to create a new route we just add a different app.post


// Handle the form POST containing the text and sid, reply with the language
var cors = require('cors'); //add the cors module code to the application
app.use(cors());
var corsOptions = {
    origin: 'http://copper.xomino.com' //allow copper to be a site which can work with the watson site
};

//note the new cors(corsOptions) parameter in the app.post function
app.post('/xpages', cors(corsOptions), function(req, res){ //when a user posts to  site.com/xpages do this code instead of the default '/'
	//stuff
}

What I then changed was the response code – this was the original code responding with text and rendering using the jade index.jade template

	//......
        result.on('end', function() {
            // add the response to the request so we can show the text and the response in the template
            request_data.translation = responseString;
            console.log('request',request_data);
            return res.render('index',request_data); //render the response using the index,jade template and passing the request_data
        })

Instead of res.render I used res.json to send the request_data object back to the browser directly.

	//......
        result.on('end', function() {
            // add the response to the request so we can show the text and the response in the template
            request_data.translation = responseString;
            console.log('request',request_data);
            return res.json(request_data);
        })

So in this way I left the default page alone (“/” server root) – the example still works – but I added a new route (“/xpages”) so that my XPage application could POST at it.

I committed the code and pushed back up to Jazz Hub, restarting the service as we went…….and low and behold success…..

w9

As you can see from the above image, I am at the copper.xomino.com website. Using the slightly modified code to now post at

I get a response from the Bluemix website with the JSON from the Translation service. You can see from the headers the CORS header is added for copper.xomino.com

w10

Note – if you go to http://xominowatsontranslate.mybluemix.net/xpages you will GET an error. This is because my node application does not have an app.get for the /xpages route

So then XPages….

Integrating the Watson Transation service into an XPage application

Once I have the working ajax code it is very simple to add it to an XPage and just pick up the field values on the fly….. I cheated to some extent and copied and pasted the HTML from the original example into my XPage….hey why not this is an example after all…

I added a couple of classes to the example so that I could easily pick out the field values…

a1

And then the jQuery code to add to the application. In this code I

  • Select the .translate class (the translate button)
  • In the click event I get the data from the form
    • the .sid select box for the language translation
    • The text value from the textbox (.theOriginal) field
  • I then submit to the the translation service as before
  • In the .done() of the AJAX request, the incoming msg.translation is then added to the .theTranslation field

a2


 The demo

As you can see from the video – I am able to:

  • type in any value
  • send it to the bluemix service
  • receive the answer and display it on the screen
  • save the original and translated values as notes documents within my XPages application
  • Firebug shows the fact that the POSTS are going to http://xominowatsontranslate.mybluemix.net/xpages

Conclusion

I think this is a great example of using a “service” on another website to be able to enhance the functionality in your own XPages application. If IBM are successful in their investigation to put Domino inside of Bluemix, this capability will all happen behind the scenes and could be easily written as one true application……bring it on… 🙂

 

PS

This exercise was particularly gratifying because it feels like a culmination of all the work I have done in XPages over the last 3 years.

  • Without the jQuery and Firebug work I did at the start of XPages development, prototyping this would have been much more tedious.
  • Learning XPages has forced me to have a better understanding of AJAX and jQuery
  • If it were not for Angular and the “Write once run anywhere” I did for MWLUG, I would not have learned about CORS.
  • If it was not for the Angular work I would not understand “routes” within an application
  • …..and now I am learning about node.js and Bluemix PaaS

Keep learning !

 

 

Angular in XPages #8 – Directives (did someone say plugins?)

In this article I will discuss Angular Directives and why they are near and dear to my heart

Directives

Directives in Angular are modular pieces of functionality which in some cases are very analogous to plugins in jQuery. According to the Angular documentation…

“At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.”

For more on the directive documentation look here – https://docs.angularjs.org/guide/directive

I have already shown and demonstrated some of the core Angular directives like ngApp and ngView. Those attributes within the HTML are the instructions to “Do Something Here”

<div ng-app="personApp">
    <div ng-view></div>
</div>

The on-last-repeat directive

Within my demo application I wanted to know when the table was finished loading. The problem is in Angular that there is no “I am finished with the template load” event. The reason is due to the asynchronous nature of the Angular code.

I wanted to load the table and then take an action on it. To do this I added a directive to the “repeat control” within my template for loading people.

The following example was completely plagiarized from this article – respect !

http://www.nodewiz.biz/angular-js-final-callback-after-ng-repeat/

You can see the on-last-repeat attribute within the first TR

    <tr ng-repeat="person in people"  on-last-repeat>
        <td>{{person.firstname}}</td>
        <td>{{person.lastname}}</td>
        <td class="zipCode">{{person.zip}}</td>
        <td class="user">{{person.username}}</td>
        <td><a class="btn btn-info" href="#/person/{{person['@unid']}}">Edit</a></td>
        <td><a class="btn btn-warning" href="#/person/{{person['@unid']}}/delete">Delete</a></td>
    </tr>

I then created a directive within my app.js to do something with the on-last-repeat

personApp.directive('onLastRepeat', function() {
    return function(scope, element, attrs) {
        if (scope.$last) setTimeout(function(){
            scope.$emit('onRepeatLast', element, attrs);
        }, 1);
    };
})

Within the code we are creating a custom “event” which can be listened for in another part of the application

  • If the last entry is triggeredhere
    then
  • $emit the onRepeatLast event within the application

Then in the PeopleListCtrl controller we set a listener –

  • $on the onRepeatLast event
  • Do something
peopleControllers.controller('PeopleListCtrl', ['$scope', '$http', 'peopleFactory',
    function ($scope, $http, peopleFactory) {
        $scope.$on('onRepeatLast', function(scope, element, attrs){
           alert('The table has loaded')
        });

a1

 

Well that is a little simple….

Yes it is but it serves to demonstrate the concept. The best part is that there are lots of people who are writing plug and play Directives for Angular – just like jQuery plugins. If I could be bothered I might even do some blog posts on useful Directives…..But is a good resource for looking at some available directives.

http://angular-js.in/

There are multiple directives for using jQuery plugins within an angular construct – this is very helpful for data binding. There are also multiple directives which are independent of jQuery and are stand along “Angular” plugins for want of a better term.

Angular.js in XPages #7 – Writing better code using Services

In this article I will discuss a better programming practice for Angular.js than was demonstrated in the previous articles within this series. I have mentioned before, part of the purpose this blog is very much a “learning in progress” for me. Without going through the previous articles I would not have been able to get to this point and write “better code”. Hopefully with that understanding, those of you who have been along for the ride will appreciate this and grow with me 🙂

Services within Angular

Within Angular there are these programmatic entities called services – and if you read around Angular programming practices (Follow @ToddMotto – http://toddmotto.com/opinionated-angular-js-styleguide-for-teams/) you will find (as I have) that adding application logic within Controllers is generally frowned upon.

“In AngularJS world, the services are singleton objects or functions that carry out specific tasks. It holds some business logic. Separation of concern is at the heart while designing an AngularJS application. Your controller must be responsible for binding model data to views using $scope. It does not contain logic to fetch the data or manipulating it.”

http://viralpatel.net/blogs/angularjs-service-factory-tutorial/

From a maintainability perspective, as well as logical code layout perspective, having functional logic within the controller is akin to writing a 1000 line LotusScript agent  – not optimal !!

I used this article by Dan Whalin to better understand how to create a Service using a factory

So what changed?

We I changed the controller around so that code in the controller that once looked like this:

 $scope.createPerson = function(event) {
            $http({
                url: '//copper.xomino.com/xomino/ainx.nsf/api/data/documents?form=fUserName',
                data: $scope.person,
                withCredentials: true,
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                }
            })
                .success(function(data) {
                    location.href = "#/people";
                })
                .error(function(data) {
                    console.log('Error: ' + data);
                });
            event.preventDefault();
            return false;
        };

now looks like this:

        $scope.createPerson = function(event) {
            dataFactory.createPerson($scope.person, event)
                .success(function(data) {
                    event.preventDefault();
                    location.href = "#/people";
                })
                .error(function(data) {
                    console.log('Error: ' + data);
                });
        };

and the service looks like this:

    dataFactory.createPerson = function (person, event) {
        console.log(person)
        return $http({
            url: urlBase+'documents?form=fUserName',
            data: person,
            withCredentials: true,
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            }
        })
    };

 

Now I know you are looking at this and saying to yourself – hang on you just copied and pasted all the code and actually made it longer and more complicated – and that would be very perceptive of you – but (and I had to make this leap to believe it myself), it is better.

My example application only really has one purpose – manage people. In a more complex application a separation of logic into like components would make sense. By using the service I have separated all my “do stuff with people” out into a people Service. When I built the next part of the application – to do with buildings for example I would create a buildings Service and manage all my building logic there.

Let the controller do it’s job and bind the data to the View and keep your logic out of the controller and into Services.

The final Code

My service (service.js)

personApp.factory('dataFactory', ['$http', '$timeout', function($http, $timeout) {

    var urlBase = '//copper.xomino.com/xomino/ainx.nsf/api/data/';
    var dataFactory = {};

    dataFactory.getPeople = function () {
        return  $http.get(urlBase+'collections/name/byFirstName5Col?open&count=3').success(function(data) {
            $scope.people = data;
        });

    };

    dataFactory.getPerson = function (id) {
        console.log('get person')
        return  $http.get(urlBase+'documents/unid/' + id)
    };

    dataFactory.createPerson = function (person, event) {
        console.log(person)
        return $http({
            url: urlBase+'documents?form=fUserName',
            data: person,
            withCredentials: true,
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            }
        })
    };

    dataFactory.savePerson = function (person, event, id) {
        console.log(id);
        return $http({
                url: urlBase+'documents/unid/' + id,
                data: person,
                withCredentials: true,
                method: "PATCH",
                headers: {
                    "Content-Type": "application/json"
                }
            })
    };

    dataFactory.deletePerson = function (id) {
            var temp = confirm('Are you sure you want to delete?')
            if (temp){
                return $http.delete(urlBase+'documents/unid/' + id)
            } else {
                location.href = "#/people"
            }
    };

    return dataFactory;
}]);

My controller

peopleControllers.controller('PersonDetailCtrl', ['$scope', '$routeParams', '$http', 'action', '$timeout', 'dataFactory',
    function($scope, $routeParams, $http, action, $timeout, dataFactory) {

        $scope.create = (action=='new' || action=="delete");

        if (action=="get") {
            dataFactory.getPerson($routeParams.docId)
                .success(function(data) {
                    $scope.person = data;
                })
                .error(function(data) {
                    console.log('Error: ' + data);
                });
        }

        $scope.home = function(){
            location.href='#/people'
        };
        $scope.createPerson = function(event) {
            dataFactory.createPerson($scope.person, event)
                .success(function(data) {
                    event.preventDefault();
                    location.href = "#/people";
                })
                .error(function(data) {
                    console.log('Error: ' + data);
                });
        };

        $scope.savePerson = function(event) {
            dataFactory.savePerson($scope.person, event, $routeParams.docId)
                .success(function(data) {
                    event.preventDefault();
                    location.href = "#/people"
                })
                .error(function(data, status, headers, config) {
                        console.log('ErrorData: ' + data);
                });
        };

        if (action=="delete") {
            dataFactory.getPerson($routeParams.docId)
                .success(function(data) {
                    $scope.person = data;
                    $timeout(function(){
                        dataFactory.deletePerson($routeParams.docId)
                            .success(function(data) {
                                $scope.person = {};
                                location.href = "#/people"
                            })
                            .error(function(data, status, headers, config) {
                                console.log('ErrorData: ' + data);
                            });
                    }, 300)
                })
                .error(function(data) {
                    console.log('Error: ' + data);
                });
        };
    }]);

 

Angular.js in XPages #6 – A People Manager CRUD application

In this article I will bring together everything discussed in the first 5 articles and demonstrate how to create you first basic CRUD application using Angular.js and XPages.

Previous articles

Introduction

In the last article we saw how routers can be used to not only create meaningful URLs but also control the application functionality. With those routers we are now able to create a functioning CRUD application which will demonstrate the core requirements for building a web based Angular.js application on Domino Data. In this article I will build on the previous article and all those in the rest of the series.

This basic Angular.js/Domino application was created with <160 lines of custom JavaScript code. It will run on Android, iPhone, IE8+, Safari, Firefox, Chrome.

As always – thanks to Dave Leedy for the fakenames.nsf database upon which this is based – and so much more !!

The routing

Inside of the app.js we create our routing table as shown below.

We have a page for the following

  • Viewing all people (/people)
  • Creating a new person (/person/new)
  • Viewing and editing a person (/person/:docId)
  • Deleting a person (/person/:docId/delete)

But as you can see form the code we have the same controller for multiple actions (PersonDetailCtrl). So to differentiate between each action within the same controller we also pass a “resolve” object containing “action: ?” which through the scope, allows us to determine what to do within the controller.

app.js

/**
 * Created by mroden on 5/4/2014.
 */

/* App Module */

var personApp = angular.module('personApp', [
    'ngRoute',
    'peopleControllers'
]);

personApp.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.patch = {
        'Content-Type': 'application/json;charset=utf-8'
    }
}])

personApp.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.
            when('/people', {    //use the people-list.html template, 'PeopleListCtrl' controller and resolve the action: list
                templateUrl: '//copper.xomino.com/xomino/ainx.nsf/partials/people-list.html',
                controller: 'PeopleListCtrl',
                resolve: {
                    action: function(){return 'list';}
                }
            }).
            when('/person/new', {    //use the person.html template, PerconDetailCtrl controller and resolve the action: new
                templateUrl: '//copper.xomino.com/xomino/ainx.nsf/partials/person.html',
                controller: 'PersonDetailCtrl',
                resolve: {
                    action: function(){return 'new';}
                }
            }).
            when('/person/:docId/delete', {    //use the person.html template, the PersonDetailCtrl controller and resolve the action: delete
                templateUrl: '//copper.xomino.com/xomino/ainx.nsf/partials/person.html',
                controller: 'PersonDetailCtrl',
                resolve: {
                    action: function(){return 'delete';}
                }
            }).
            when('/person/:docId', {    //use the person.html template, the PersonDetailCtrl controller and resolve action: get
                templateUrl: '//copper.xomino.com/xomino/ainx.nsf/partials/person.html',
                controller: 'PersonDetailCtrl',
                resolve: {
                    action: function(){return 'get';}
                }
            }).
            otherwise({    //if all else fails then just go to people
                redirectTo: '/people'
            });
    }]);

The controller

Within controller.js we can see the two controllers peopleControllers as we had before

  peopleControllers.controller('PeopleListCtrl', ['$scope', '$http',

and

  peopleControllers.controller('PersonDetailCtrl', ['$scope', '$routeParams', '$http', 'action',
    function($scope, $routeParams, $http, action) {

Within the PersonDetailCtrl we now some IF statements – depending on what resolve variable is passed into the controller, we determine what action to take.

The resolve parameter passed in is “action:” and that is added to the controller as a parameter ‘action’. Using this ‘action’ we know the users intention.

We also create two scoped functions $scope.createPerson and $scope.savePerson. These actions will be linked into button clicks as we will see later in the article.

controller.js

/**
 * Created by mroden on 5/05/2014.
 * With help from - http://scotch.io/tutorials/javascript/creating-a-single-page-todo-app-with-node-and-angular
 */

var peopleControllers = angular.module('peopleControllers', []);

peopleControllers.controller('PeopleListCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $http.get('//copper.xomino.com/xomino/ainx.nsf/api/data/collections/name/byFirstName5Col?open&').success(function(data) {
            $scope.people = data;
        });
    }]);

peopleControllers.controller('PersonDetailCtrl', ['$scope', '$routeParams', '$http', 'action', '$timeout',
    function($scope, $routeParams, $http, action, $timeout) {

        console.log("Action1: "+action);
        $scope.create = (action=='new' || action=="delete");

        if (action=="get") {    //get the user data from the DDS Document REST service
            $http.get('//copper.xomino.com/xomino/ainx.nsf/api/data/documents/unid/' + $routeParams.docId)
                .success(function(data) {
                    $scope.person = data;
                    console.log($scope);
                })
                .error(function(data) {
                    console.log('Error: ' + data);
                });
        }

        $scope.createPerson = function() {   //POST the $scoped person data to the DDS and create a new document
            $http.post('//copper.xomino.com/xomino/ainx.nsf/api/data/documents?form=fUserName', $scope.person)
                .success(function(data) {
                    location.href = "#/people"
                })
                .error(function(data) {
                    console.log('Error: ' + data);
                });
        };

        $scope.savePerson = function() {    //Create a PATCH request and send the updated $scoped person data to the DDS Document
                $http({
                    url: '//copper.xomino.com/xomino/ainx.nsf/api/data/documents/unid/' + $routeParams.docId,
                    data: $scope.person,
                    method: "PATCH"
                })
                .success(function(data) {
                    location.href = "#/people"
                })
                .error(function(data) {
                    console.log('Error: ' + data);
                });
        };

        if (action=="delete") {   //Get the person data - then delay slightly - then as the user if they want to delete
            $http.get('//copper.xomino.com/xomino/ainx.nsf/api/data/documents/unid/' + $routeParams.docId)
                .success(function(data) {
                    $scope.person = data;
                    console.log($scope);
                    $timeout(function(){  //delay 300ms and then ask the user to confirm deletion
                        var temp = confirm('Are you sure you want to delete?')
                        if (temp){    //if yes delete then send a DELETE request to the DDS Document REST service
                            $http.delete('//copper.xomino.com/xomino/ainx.nsf/api/data/documents/unid/' + $routeParams.docId)
                                .success(function(data) {
                                    $scope.person = {};
                                    location.href = "#/people"
                                })
                                .error(function(data) {
                                    console.log('Error: ' + data);
                                });
                        } else {
                            location.href = "#/people"
                        }
                    }, 300); // time here

                })
                .error(function(data) {
                    console.log('Error: ' + data);
                });

        };

    }]);

Update people-list.html

We update the people-list with two new “buttons”. An “Add Person” button and a “Delete” button.

a1

Both buttons route to person.html, but the DELETE option loads the person’s information.

If we look in app.js we can see that #/person/new sends the action: new to the controller. But in the controller we are not actually looking for a “new” action. At initial glance though in the controller we are not looking for if (action==’new’). But we are doing is using it for something subtle but no less important.

        $scope.create = (action=='new' || action=="delete");

What we are doing is simply setting up a scope$ variable for “create”. When we come to the person.html template we will see why.

people-list.html

<pre><div class="row" style="width: 50%">
    <div class="col-sm-2">
        <a class="btn btn-default" href="#/person/new">Add Person</a>
    </div>

</div>
<table class="table table-striped">
    <thead>
    <tr>
        <th>First Name</th><th>Last Name</th><th>Zip</th><th></th><th></th>
    </tr>
    </thead>
    <tbody>

    <tr ng-repeat="person in people">
        <td>{{person.firstname}}</td>
        <td>{{person.lastname}}</td>
        <td>{{person.zip}}</td>
        <td><a class="btn btn-info" href="#/person/{{person['@unid']}}">Edit</a></td>
        <td><a class="btn btn-warning" href="#/person/{{person['@unid']}}/delete">Delete</a></td>
    </tr>

    </tbody>
</table>

Deleting a Person

Clicking the Delete Button performs the following:

  • Changes the URL to #/person/UNID/delete
  • Which is picked up by the router
    • Which uses the personController
    • that then executes the When(‘/person/:docId/delete’, {
    • Which uses the person.html
    • Which in turn resolves the action: delete
  • $scope.create is set to true
  • The person “form” is loaded and filled with data from Domino Data Service
  • Pause for 300 milliseconds using $timeout
  • The controller then acts on the delete action
    • if (action==”delete”) {
    • Confirms do you want to delete
    • var temp = confirm(‘Are you sure you want to delete?’)
    • IF true then loads the http DELETE at the DDS URL for the document
    • $http.delete(‘//copper.xomino.com/xomino/ainx.nsf/api/data/documents/unid/’ + $routeParams.docId)
    • and returns the user back to the original list
    • location.href = “#/people”

a2

 

Adding a new person

When we click the Add person button:

  • The URL is changed to #/person/new
  • The router picks up the change and loads person.html
  • resolves the action: new
  • $scope.create is set to true
  • The person.html template is loaded with no data – there is no action in the controller associated with new to load any

ng-show / ng-hide

We brushed over the $scope.create for delete but lets now look at it in the context of a new Person. Looking at the form for editing  person we see a “Create” button whereas for an existing person we see a “Save” button. Looking at the code for the two buttons closely we can see two new directives – ng-show and ng-hide

    <div class="col-sm-2">
        <button class="btn btn-default" ng-click="savePerson()" ng-hide="create">Save</button>
        <button class="btn btn-default" ng-click="createPerson()" ng-show="create">Create</button>
    </div>

The ng-show and ng-hide directives are used in conjunction with the $scope.create to appropriately show and hide the buttons. So with no JavaScript code written we are able to apply a programmatic hide/when to the buttons based on the $scope data. That’s cool !! 🙂

a4

Once the data is entered and we click create – the ng-click directive kicks in and calls the “createPerson()” function. Back in the controller we created the $scoped createPerson() function…

        $scope.createPerson = function() {
            $http.post('//copper.xomino.com/xomino/ainx.nsf/api/data/documents?form=fUserName', $scope.person)
                .success(function(data) {
                    location.href = "#/people"
                })
                .error(function(data) {
                    console.log('Error: ' + data);
                });
        };

In this function we perform a “POST” at the DDS api/data/documents?form=fUserName which creates a document based on the fUserName function. The data POSTed is the $scope.person. We can see the JSON using firebug sent back to the server. We are then returned to the people-list and can see the new entry loaded.

a3

Editing an existing person

When clicking on the Edit button from the people-list.html template a person is loaded as we saw in the previous article. Looking back at the person.html “Save” button which is now visible because $scope.create is not equal to true – we can see the save button uses ng-click to call the “savePerson()” function. Once again we look to the controller.js and see where this was created.

        $scope.savePerson = function() {
                $http({
                    url: '//copper.xomino.com/xomino/ainx.nsf/api/data/documents/unid/' + $routeParams.docId,
                    data: $scope.person,
                    method: "PATCH"
                })
                .success(function(data) {
                    location.href = "#/people"
                })
                .error(function(data) {
                    console.log('Error: ' + data);
                });
        };

In this case we are using the calling $http using a slightly different pattern. I want to do a PATCH to only modify the data which has changed within the document. Out of the box Angular does not have a $http.patch method so we have to create the http call manually. We provide the url, data and method as shown above. To allow this on the server we have to enable the PATCH method within our Domino Website document (a sign that you have not got this enabled will be a 405 method not permitted error).

a5

Once we click the Save button we can see the JSON being sent to the server, using the PATCH method, and we are then routed back to the front page.

a6

Here’s a question for you guys – as you can see from the PATCH the data passed back a lot more information than just the firstname, lastname and zip  – why and where did the rest of the @fields come from??

🙂

person.html

<legend>A Person</legend>

<div class="row" style="width: 50%">
    <div class="col-sm-4">
        <label>First Name</label><br/>
        <input class="form-control" name="firstname" type="text" value="{{person.firstname}}" ng-model="person.firstname">
    </div>
    <div class="col-sm-4">
        <label>Last Name</label><br/>
        <input class="form-control" name="lastname" type="text" value="{{person.lastname}}" ng-model="person.lastname">
    </div>
    <div class="col-sm-4">
        <label>Zip</label><br/>
        <input class="form-control" name="zip" type="text" value="{{person.zip}}" ng-model="person.zip">
    </div>
</div>
        <br/>
<div class="row" style="width: 50%">
    <div class="col-sm-2">
        <a class="btn btn-default" href="#/people">Back</a>
    </div>
    <div class="col-sm-2">
        <button class="btn btn-default" ng-click="savePerson()" ng-hide="create">Save</button>
        <button class="btn btn-default" ng-click="createPerson()" ng-show="create">Create</button>
    </div>
</div>
<hr />

In this article the index.html did not change from the last article

Thoughts and Questions

We have Created, Read, Updated and Deleted data using Angular.js to control the Domino Data Services REST service. Have we created an XPages application? In the literal sense of the word(s), no I don’t think we have.

  • We have not created a single XPage
  • We have not used an XPages control
  • We have used out of the box DDS which comes with the server not with XPages.

So this is just a Domino application then?

  • We used Domino Data Services
  • Our data is coming from an IBM Domino database
  • We didn’t use any XPages or code which has to be pre-compiled on the server
  • We did however take advantage of the fact that this is a >R8.5 server/database which allows access to Package Explorer and syncing of an ODS
  • Sooooo – yes it is just a Domino application but not the one you grew up with 15 years ago

Could we have written it quicker in XPages?

  • We I certainly could have at the beginning, because I had to learn Angular as I was doing it – but that wasn’t the point of the question was it….
  • Yes we could have created it with less “XPages” code. IBM has provided some nice tools to allow us the “developer” to take action on data without having to think to hard about the inner workings of it.
  • That being said though, I believe an experienced Angular developer would be able to put this together just as quick as an experienced XPages developer.

So then what have we gained Marky?

  • Well I for one can now put “Angular.js” on my résumé as something I have at least a basic understanding of
  • Understanding how a web based application like this interacts with a NoSQL system gives me more flexibility in problem solving customer requirements
  • This application uses the best NoSQL database system in the world – that is never a bad thing
  • There are actually some other major advantages to programming an application in this manner. I am working on them for a future demonstration and presentation at MWLUG (teaser intended) – All in good time 🙂

Overall, the term “XPages development” seems to encompass more than just the out of the box “XPages” tools which IBM have provided . It has (to me anyway) come to mean the whole server package and not just XPages tooling. With that has come a broadening of the mind into truly modern web development using the modern Domino development platform – I am perfectly OK with calling this “Angular.js in XPages”.

Conclusion

Over the last few article we have opened the covers on the new web technology that is “Angular.js”. We built a CRUD application using data from arguably the world’s most secure NoSQL system. I love it 🙂

Download the example

The example can be downloaded from this link – but some work will need to be done to make it work on your server:

  • Change the URLs in app.js and controller.js to your server
  • Make sure you have PATCH enabled on your server website document (requires restart)
  • You must enable Domino Data Services on your website document
  • You must ensure DDS access to your database (DB Properties)
  • You must enable DDS access to your view
  • You will find all the files in the Package Explorer / WebContent folder for the database.

PS

For the PATCH question I asked – here’s a tip – what’s in $scope ?

Angular.js in XPages #5 – Routing

In this article I will show how angular using routing to create a bookmarkable URL string and how that fits together with additional controllers. This will start us on the path to creating our basic CRUD application. This article is based on the Routing and Multiple views tutorial 

Routers

Way back when the world was young (in internet terms a couple of years ago), when single page apps were all the rage, it was noticed that there was a significant drawback to only having one URL index.html; it was useless as a bookmark. Even worse it was impractical to send a link to a page within the application, and that made for some serious limitations.

Routing was created as a manner to not only provide a URL which could be referenced within the application, but it also helped to separate the code into discrete functional areas within the application. This route, this controller, this model and so on.

In Angular –“Providers are objects that provide (create) instances of services and expose configuration APIs that can be used to control the creation and runtime behavior of a service. In case of the $route service, the $routeProvider exposes APIs that allow you to define routes for your application.”

So we add the angular-route.js file which was in the original download to our database in the angularjs folder

app.js

Beginning our path towards true code separation we are going to create a new app.js file which will contain the architecture for the application. Our app.js file will contain the following:

  • The angular module and the dependencies for that module (previously we had a module with no dependencies)
  • The route configuration for the new application

In this way we are defining what our application needs to run (as an Angular app) and the route mapping (as we will see) for “this URL – this Template”

Because we are moving the module code up to the app.js we also need to create a ngView for the app rather than the ng-controller like we had before.

This will mean:

  • a change to the container DIV within index.html
  • moving the HTML to a template and not in the index.html itself

Overall we are not going to change that much code, we are just going to move it around to make more sense from an application perspective rather than a demo.

/**
 * Created by mroden on 5/4/2014.
 */

/* App Module */

var personApp = angular.module('personApp', [

    'ngRoute',
    'peopleControllers'
]);

personApp.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.
            when('/people', {
                templateUrl: 'partials/people-list.html',
                controller: 'PeopleListCtrl'
            }).
            when('/person/:docId', {
                templateUrl: 'partials/person.html',
                controller: 'PersonDetailCtrl'
            }).
            otherwise({
                redirectTo: '/people'
            });
    }]);

You can see from the code above that we are going to create two new files – people-list.html and person.html. These are the two templates we are going to “route” to in this part of the application

 people-list.html

The people list template is replacing the HTML code we had before in the index.html. This time though instead of copying the mustache layout as we did before we are actually going to go for a simple table. In an analogous manner to using a repeat control in XPages we create the shell of the table and use the rows as the repeating element wrapper.

<table class="table table-striped">
    <thead>
    <tr>
        <th>First Name</th><th>Last Name</th><th>Zip</th><th></th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="person in people">
        <td>{{person.firstname}}</td>
        <td>{{person.lastname}}</td>
        <td>{{person.zip}}</td>
        <td><a class="btn btn-info" href="#/person/{{person['@unid']}}">Edit</a></td>
    </tr>

    </tbody>
</table>

If you look closely at the Edit button code here you will see that we are manually creating a route map for the person. The {{person[‘@unid’]}} template pointer is going to be filled with the JSON Object nth value and the “@UNID” parameter therein. Remember that @ symbols are classed as parameters and not real key pair values within JSON (*again dumb dumb idea IBM*). So in this case we cannot refer to it as person.@unid that would fail.

Looking at the HTML generated you will see that this creates a URL which may seem strangely familiar.
a1

And that was constructed from the DDS JSON data as we saw before
a2

person.html

In the person template we are going to display the 3 fields as if they were editable. The analogy here is between an XPage and the data binding to Document Source. In this case the source is the JSON string data retrieved from the DDS.

<legend>A Person</legend>

<div class="row" style="width: 50%">
    <div class="col-sm-4">
        <label>First Name</label><br/>
        <input class="form-control" name="firstname" type="text" value="{{person.firstname}}">
    </div>
    <div class="col-sm-4">
        <label>Last Name</label><br/>
        <input class="form-control" name="lastname" type="text" value="{{person.lastname}}">
    </div>
    <div class="col-sm-4">
        <label>Zip</label><br/>
        <input class="form-control" name="zip" type="text" value="{{person.zip}}">
    </div>
</div>
        <br/>
<div class="row" style="width: 50%">
    <div class="col-sm-12">
        <a class="btn btn-default" href="#/people">Back</a>
    </div>
</div>

<hr />

The controller

Within the controller.js file we now need to manage not only the download of data for the people, but also for the person who will be subsequently opened. In this case we need two controllers to handle the People and the Person. Both controllers access the DDS data, first for the view information and secondly for the document information.

If you look at PeopleListCtrl you will see only two dependencies ($scope and $http), whereas PersonDetailCtrl needs 3 ($scope, $http and $routeParams). This is because the People feed is always at the root of the application and therefore does not need Route information. The “Person” (as we saw above) is generated from the URL #/person/UNID.

Once the person and UNID is opened as a URL the controller then creates another ajax call to the DDS document service corresponding to the UNID in the route map. The JSON string downloaded is then turned into an object and $scope.people turned into a scoped object.

var peopleControllers = angular.module('peopleControllers', []);

peopleControllers.controller('PeopleListCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $http.get('api/data/collections/name/byFirstName5Col?open&').success(function(data) { //DDS View feed
            $scope.people = data;
        });
    }]);

peopleControllers.controller('PersonDetailCtrl', ['$scope', '$routeParams', '$http',
    function($scope, $routeParams, $http) {
        $http.get('api/data/documents/unid/' + $routeParams.docId).success(function(data) { //DDS Document Feed
            $scope.person = data;
        });
        console.log($scope)
    }]);

 The result

We have created a simple demonstration of how we can using routing to create two different pages within an application


a3

a4

 

Conclusion

In this article we have seen the beginnings of a real application. The application is taking shape in an easy to manage , separated, set of code modules which reflects out MVC approach to the data, the HTML and the control thereof.

  • app.js
    • Provides the architecture for the application by defining the routing and the module dependencies
    • The routing map defines:
      • the URL to look for
      • the template to use to display the data
      • the controller to use to manage that data
  • controller.js
    • Contains the controllers which determine what happens based on the definitions as described in the route map
  • templates
    • Simple HTML templates which are used to display the bound data on the screen for the user

 

In the next article we will look at expanding this display application into a full CRUD capable application.
Updated
Fixed the routing code for a person thanks to comment from Angelo

Angular.js in XPages #4 – Using Domino Data

In this article I will demonstrate how to use Angular.js to access Domino Data and display it in place of the hard coded data we used in the previous article.

Introduction

This article is based off the Angular developer tutorial on XHR and dependency injection . It is essential you go and read that article before continuing. It explains how dependency injection works, why it is used and about Angular services.

Modifying the controller

In our previous article we used a hard coded json string of data directly within the controller. In a real application though, the data will be dynamic and need to be pulled directly from the data repository as and when needed.

Injecting the $http service

When the controller is constructed we are able to pass to it an unspecified number of services which the controller code are dependent on. In a sense it is just like creating your XPage, needing to use jQuery and making sure the jQuery library is loaded on the page before you use a $(‘selector’). The jQuery library is a dependency of the XPage code running the plugin.

The previous controller looked like this

/**
 * Created by mroden on 4/25/2014.
 */

var personApp = angular.module('personApp', []);

personApp.controller('PersonCtrl', function ($scope) {
    $scope.people = [
        {
            "@entryid":"1-431C28F894B0548185257C22000A8403",
            "firstname":"Agnes C.",
            "lastname":"Smith",
            "address":"24256 Leisure Lane"
        },
        {
            "@entryid":"2-4ED02366A420D23985257C4F000B0BD7",
            "firstname":"Albert",
            "lastname":"Scoggins",
            "address":"3525 Koontz Lane, second"
        },
        {
            "@entryid":"3-6D8120FA75B4BCCF85257C4F000B0B5D",
            "firstname":"Alejandra",
            "lastname":"Dodge",
            "address":"3044 Simpson Avenue"
        }
    ];
});

And out new controller looks like this

/**
 * Created by mroden on 4/25/2014.
 */

var personApp = angular.module('personApp', []);

personApp.controller('PeopleCtrl', function ($scope, $http) {
    $http.get('http://copper.xomino.com/xomino/ainx.nsf/api/data/collections/name/byFirstName5Col?open&')
         .success(function(data) {
            $scope.people = data;
         });
});

So you can see that the $http service has been added as a service added to the instantiation of the personApp controller PeopleCtrl. The code has also obviously got much shorter because he are not hard coding the data in here.

**yourDatabaseJSONFeed**

In Domino (R9) we have a number of methods available to us to create JSON data securely:

  • LotusScript/Java agent
  • Form with dataType set
  • XAgent (SSJS and/or Java)
  • ExtLib REST service (out of the box and custom REST)
  • Domino Data Services

For the sake of these examples I am going to use Domino Data Services (DDS). For more information on what they are and how to set them up securely in your database check out these links:

In the example above we used the Domino Data Services the URL for provides the following

http://copper.xomino.com/xomino/ainx.nsf/api/data/collections/name/byFirstName5Col?open&#038;

[
  {
      "@href":"\/xomino\/ainx.nsf\/api\/data\/collections\/name\/byFirstName5Col\/unid\/C5543E624FF5042805257838007ABDA3",
      "@link":
      {
          "rel":"document",
          "href":"\/xomino\/ainx.nsf\/api\/data\/documents\/unid\/C5543E624FF5042805257838007ABDA3"
      },
      "@entryid":"1-C5543E624FF5042805257838007ABDA3",
      "@unid":"C5543E624FF5042805257838007ABDA3",
      "@noteid":"18D6",
      "@position":"1",
      "@siblings":1298,
      "@form":"fUserName",
      "firstname":"Adam",
      "lastname":"Saenz",
      "address":"2519 Custer Street",
      "city":"ROCKWOOD (SOMERSET)",
      "state":"PA",
      "zip":15557
  },
   .......

And as you can see from this the firstname, lastname and address fields are supplied in the REST JSON feed.

Note on testing

If you try and load the code up in the Webstorm debugger you will get the following CORS problem – nothing works…..

a1

When your Browser is in the “localhost” domain it cannot pull ajax requests from the xomino.com domain – it is a security feature of the browser and server to prevent cross site scripting. Read more about CORS here.

This is why (as we saw in the previous article) we integrated the development environment with the Domino ODS. Because I am working on a sync’d version of the database – all I have to do is go over to the index.html within the Domino database on my server and it works (because we are in the correct domain)

a2

 

Conclusion

What we have seen in this article is a simple evolution of the controller to allow it to pull real data from the server rather than using hard coded Data. In the next article we will look at further CRUD operations.

 

WebSockets comes to XPages!! Awesome – Awesome – Awesome

In this article I will introduce and discuss the OpenNTF WebSockets OSGI plugin by Mark Ambler. The websocket plugin posted to Mark Ambler is based on the http://java-websocket.org/ project.

I realize I am not the first person to play with a websocket server on top of a domino database. I know of at least 4 other people who have at least done their own POC for this. But this is the first time I have got my hands on it 🙂 I’m a little excited……

Brief overview of WebSockets
I already wrote about the reasons for websockets in XPages. But to recap, WebSockets allows me the developer to PUSH messages out to logged in users without them asking for it. This reduces network traffic and creates a new paradigm for fluid data update.

What I will be doing over the next few blog posts is demonstrate examples of why WebSockets fundamentally changes how we architect our web apps in the future. Yes it is that significant in my mind.

How does the Domino integration work?

  • Download the OpenNTF project, unzip and follow the instructions in the PDF file.
  • Make sure you sign the update site before deploying
  • Install the update site in Domino Designer and restart
  • Understand that this is not port 80….this is demonstration right now and not production ready.

Once you have the plugin installed and up and running application you will be able to use the chat.nsf example to demonstrate for yourself what is going on. This is only intended to be an example of what is possible, not a production app. replacing sametime 🙂

From a Domino perspective, The core of the application is the websocket.nsf database. In there if you look at the Broadcast Example Agent you will see how it works.

w1

This article was written based on code release 1.0.7

By creating a document in the database with the appropriate fields, the websocket OSGI code picks up the document from the view and routes it out to the users.

The websocket.nsf database tracks users in the vUsers view and from there we can ascertain the unique code assigned to each logged in user.

Using that websocketID listed in the view we are able to ensure that the appropriate message is transmitted to the appropriate user.

To extend this into something I can use I create an SSJS function which will look up the socketID – in this case I do not need to know the ID – just the username.

function createMessage(socketID, msgObj){

	var db:NotesDatabase = session.getDatabase("","websocket.nsf",false);
	var doc:NotesDocument = db.createDocument()
	var online = ""
	if (!socketID){
		var view = db.getView("vUsers")
		println("rec: "+msgObj.recipient)
		var user:NotesViewEntry = view.getEntryByKey(msgObj.recipient)
		if (user){
			socketID = user.getColumnValues()[1]
			online =  user.getColumnValues()[2]
			println(socketID)
		}
	}

	if (socketID && (online=="ONLINE")){
		doc.replaceItemValue("Form", "fmSocketMessage")
		doc.replaceItemValue("from", msgObj.from)
		doc.replaceItemValue("to", socketID)
		doc.replaceItemValue("sentFlag", 0)

		//The msgObj will come in as an Array of Json - we need to convert that into a multi-value notes field
		//This is planned to be fixed to apss the JSON straight through in a later release

		for (var i=0; i<msgObj.data.length; i++){
			var temp = msgObj.data[i]
			for (key in temp){
				if (i<1){
					var item:NotesItem = doc.replaceItemValue("data", key+"="+temp[key])
				} else {
					item.appendToTextList(key+"="+temp[key])
				}
			}
		}
		doc.replaceItemValue("text", "")
		doc.save()
	} else {
		println("WebSocket messgae not sent")
	}
}

I can then call this function from an XPages button (or anywhere else for that matter) and pass in the data as an object.

	<xp:button value="Send Message" id="button1">
		<xp:eventHandler event="onclick" submit="true" refreshMode="complete">
			<xp:this.action>
				<xp:executeScript>
					<xp:this.script><![CDATA[#{javascript:
						var msgObj = {}
						msgObj.recipient = context.getUser().getDistinguishedName()
						msgObj.from = "Marky demo"
						msgObj.data = [{"beer": "english"}, {"lager": "french"}]
						createMessage("", msgObj)
					}]]></xp:this.script>
				</xp:executeScript>
			</xp:this.action>
		</xp:eventHandler>
	</xp:button>

Looking at the chat example below which I have also slightly modified to console.dir the output so that it is readable we can see the message is sent to the client

w2

 

In a more advanced demonstration I added a field to the right hand form so that i can pass through my own JSON – the video below shows this best 🙂

This was recorded at 1920 resolution so it appears blurred on youtube – CHANGE THE QUALITY to 720HD and that will fix it

OpenNTF WebSockets OSGI plugin

Mark Ambler

Caveat

Please bare in mind this is not production ready code – and it may never be……

Because there are two servers running (domino and websocket) the websockets are current running over a non-standard port. I believe IHS can be used as a proxy to fix that.

As a proof of concept though and to get the information out to the community and IBM (hint hint) this is a great step forward in capabilities.

This is a great example of using and OSGI plugin and the Java code in Domino to access a Java server and transmit data – very cool !

Conclusion

There is no polling of the server by the client. There are zero unnecessary http calls

We can have any application with an appropriate update, review the users who are logged in and update their web page with the appropriate data.

THIS IS AWESOME!!!!!!!!!!!!

Awesome!!!!!

Next – more examples

I feel a series coming on…….:)

 

Update

You know a project is moving along when this blog post was already out of date by the time I am ready to post it – but rather than waste it because there is good information in here – here’s the disclaimer.

This post is based on v1.0.7 of the webshell code release – as of v1.0.8 the JSON data is being passed via rich text which allows for pre-formatting server-side before sending it out. This also allows for more complex JSON creation than multi-value text fields can handle – thanks Mark – more about that soon !!

This change was based on my request for a feature on the github site

If you want to see this improve and progress – get involve – play with the code and make requests for changes – like everything OpenNTF – the more you play with it and the more people are involved – the better it will become !

 

Angular.js in XPages #3 – The first app

In this article I will recreate one of the simple Angularjs.org developer tutorials and relate it to how we would build an equivalent XPages application.

Create the database

As described in the previous article, set up a Domino database with an ODS. Then link your Webstorm to the new ODS structure.

Download the Angular code from https://angularjs.org/ it will be an 8M download. Opening the zip file you will see a lot of “angular files”. These are “Dependency files” and are separate functional areas of Angular which can be included within your application as necessary. Although programatically not the same, the concept is similar to the way we use Dojo in XPages.

a1

For the moment we are going to add the following to our database. for the sake of clarity I have added them in an angularjs folder in the webContent folder of my database. I have also added bootstrap (to keep Mark Leusink happy).

a2

I then move over to my Webstorm and add the project

a3

 

CDN alternate

You absolutely do not have to download the files and have them reside locally – you can link to the angular code through the Google CDN site. This is entirely up to you.

Quick MVC

MVC stands for “Model View Controller” and unlike traditional Domino development, forces good coding practices and separates UI components from application logic. This methodology has been brought closer to reality in XPages development using good Java coding practices but is still rather elusive for those using SSJS.

  • The Model is the data created by the application
  • The View is the HTML representation of the data through the use of Templates
  • The Controller is  the application code which is used to determine the way the Model is populated and displayed.

 

Our first Angular app

I am going to recreate the Mustache.js article I wrote earlier this year and show how to use a front end Angular repeat to create a basic page of data.

I am not going to repeat everything which you can read for yourself in the Angular tutorial. The tutorials are great and frankly better written than I can. So with the assumption that you at least understand the terms I will attempt to explain what I am doing.

Create Our HTML File 

I then create a new angular HTML file in Webstorm by right clicking on the WebContent and creating new HTML file. (You will notice that you can actually create your own Template so that in the future you can have a preset angular shell set up and ready to go if you like !)

a4

 

The View and Template

Within the HTML file we are going to create a simple DIV and manually attach a controller to it using an angular directive. The ng-controller in this case tells the Angular code to “Do your stuff Here”. Kinda like an <xp:panel> where we control a section of the functionality without affecting the rest of the XPage.

a1

You will also notice that I added ng-app =”personApp” to the HTML tag at the top of the page. That associates the application with this whole page. More on that later.

Within the PersonCtrl we are going to add our template code (once again akin to what we did in the mustache example except there we used a <script> tag to contain our template HTML)

a1

So there is a little to talk about here.

The Repeat control

The Angular “repeat control” is an element (any HTML element) with the ng-repeat in it. In this case we are looking to repeat all Person within People (coming from the controller in a minute). Seems simple enough to read and understand

        <div ng-repeat="person in people">
        ...
        </div>

 The data binding

                    {{person.firstname}} {{person.lastname}}

The data-binding using the same {{ STUFF }} notation as the mustache example. Double Curly Brackets denotes the template placeholder for *DATA HERE*

The Model and Controller

We are going to create a new directory and within it the controller.js file. That file contains the information necessary to create the page we are looking for.

The controller contains two parts

  1. The code which runs Angular in the first place
  2. The controller code which says put this data *there*

 

/**
 * Created by mroden on 4/25/2014.
 */

var personApp = angular.module('personApp', []);

personApp.controller('PersonCtrl', function ($scope) {
    $scope.people = [
        {
            "@entryid":"1-431C28F894B0548185257C22000A8403",
            "firstname":"Agnes C.",
            "lastname":"Smith",
            "address":"24256 Leisure Lane"
        },
        {
            "@entryid":"2-4ED02366A420D23985257C4F000B0BD7",
            "firstname":"Albert",
            "lastname":"Scoggins",
            "address":"3525 Koontz Lane, second"
        },
        {
            "@entryid":"3-6D8120FA75B4BCCF85257C4F000B0B5D",
            "firstname":"Alejandra",
            "lastname":"Dodge",
            "address":"3044 Simpson Avenue"
        }
    ];
});

Creating an angular module

The angular.module code in the example above makes the HTML tag with ng-app=”personApp” (The HTML tag) into the module we are creating. In more complex applications there are going to be multiple modules in multiple areas of the page but in this case nice and simple just the one.

The controller binds to PersonCtrl (our DIV ng-controller=”PersonCtrl”) and then returns the $scope.people data to it as a function.

$scope is a special name for the angular scope within the defined module. It contains all the information abou tthe module but does not have access to anything outside of it. In this case we are injecting the data into the application at load time so that it can be displayed.

The results

Loading the application up in the debugger we can see the result we are looking for

a2

Back in Domino ?

I went back over to DDE and it has refreshed automagically – There are my new files on the ODS and synced to the server database

a3

I opened the index.html on my server and with ZERO additional effort I now have my simple app in a secure database requiring login – nice eh 🙂

a5

Conclusion

In this short article I have recreated one of the simple examples from the Angular.js developer tutorials and tried to relate it to the XPages development environment. In this case we have static JSON which is a nice example to start with, but not really application-worthy. in the next article we will look at getting real data from the application.

 

PS

Yeah I noticed in review that “Hello My is Mark Roden” is not the most correct English I have ever used in an example – but the code still works 🙂

And the gloves are off……

Picture this: I have been away for 5 days and during that time “someone” has been posting cryptic comments on twitter about how the next notesin9 is going to be different….and scaring me.

So I am waiting at the airport this afternoon, about to board my plane home and I get this link from this “friend” who tells me to watch the new video it and enjoy. I download it and watch it on the plane. People start to look at me funny as I start to snort and giggle at my phone.

I am sitting here are 30,000 feet laughing my ass off at the video. Not only at the brutal use of apparently free Child labor, the amazing feminine  likeness of my voice and the awesome lip synching 🙂

The video is of course the latest notesin9 episode 141 and for the record Dave is smarter than he let’s on!

Dave is a good friend and I metaphorically love him to bits – I loved the episode – loved the fact that he took so much time to create it – love the creativity – love the humor / love love love. Thank you I am very flattered.

The gloves are off is a reference I get, something to do with Canadians and this guy called Neal who plays for the Penguins…..I dunno…anyway….

Dave’s overall point is right, horses for courses, the right language for the job and the right job for the customer.

He is right that front end and back end  are 50% equal in importance. The end user doesn’t care about back end and it has 0% importance to them. Your IT manager cares nearly 100% about the back end code and making it maintainable. Who is your customer? 😉

This healthy discussion will go on forever apparently and only serves to demonstrate how complex XPages can be. To IBM’s credit they have created a technology which is equally at home as:

The original and arguably still best secure NoSQL data store who’s primary task is serving JSON to a JavaScript framework such as Angular or backbone

An interoperable, integration platform which provides an application building capabilities with simple drag and drop data controls and a powerful back end data parsing capabilities.

and everything in between.

Love ya Dave 🙂 thanks for the laugh.

I can’t wait to get off the plane and see everyone else’s reaction 🙂

PS
Next time we have a beer I’ll point out the significant errors in your video 😉

When the community comes together we get the right answer

Last week I posted why JavaScript is more critical a skill to learn than Java. There was an outpouring of comments, discussion and responses unlike any I have seen in a while.

To give a little more background as to why I decided to post: I was not to be antagonistic or instigate a storm in a tea cup. It was because for the third time in 2014 I had been told by a notes developer something along the lines of “I can’t learn XPages because I have read that you need to learn Java and I do not have the time/skill to do so”.

For right or wrong the perception gleaned from community blogging was that was Java was required learning, which is not the case. And so I blogged.

What I did not forsee was the outpouring and wealth of knowledge bestowed on my blog comments by more that 20 members of the XPages community. I believe what was created was much much better than the original post alone and is one of the best examples of the community working together to get the *right* information out there.

The comments are unfortunately not the easiest thing to follow as there are so many of them (which is great) so what I will be doing in the near future is putting together a compilation of the sentient parts of the conversation ( ignoring the pointless sarcasm) as a resource for all.

In the mean time I wanted to say thank you one an all who contributed and to let you know I got so much more out of the post then I ever hoped for.

Thanks !!!