Creating a really basic angular directive with typescript

We're going to build a simple search angular directive using typescript. So it is going to look like this. As you type through, your search text changes. When you hit, search it fakes search results.

This is how our typescript look like.  It is not so complicated and extensively documented, in case you have any question. Please spend some time go  through the code. It is as basic as it can get. 

Lets walk through anyway.  

Line #1 - we import all angular's 1 typings. 

Line #5 - we declare an interface ISimpleSearchScope for the scope (this is the $scope - that you would use in angular1), just so we can put some intelli-sense to our code. :)

Line #11 - is where we define our SimpleSearchDirective. It inherits from ng.IDirective. 

Line #12 - binds a controller to our directive. If we do not do this, Search() function will not work but your, filter expression will {{}}. Just so we know the difference. 

Line #14 - controllerAs gives our controller a different name. 

Line #24 - is really a helper method which be used on line #26 to expose our directive. 

Line #32 - Is our controller and noticed we used 'ISearchSimpleScope' in our controller, so we can be sure we are working with the correct properties. In this case, it is called 'SearchResults' and 'SearchText'

Line #46 - We got pretty much all our component up and running, now it is time to load it with Line #49. 

What would our html look like? Well it looks like this..... 

Some development notes 

If you take out line #35 ->  static $inject = ["$scope"]; .you can be sure, you control is not going to work. Please make sure you have your angular1 other external dependencies specified here, like $http, $scope and etc.

Unit testing SimpleSearch controller 

Let's go ahead and create our unit test for SimpleSearchController. We will  use angular-mock for properly creating our. As you can see, we are using rootscope to create our scope instance. Even though this is scope instance, but we do have access to our 'SearchText' and 'SearchResults'.


Popular posts from this blog

Solving Sonarqube :- Project was never analyzed. A regular analysis is required before a branch analysis

spark - pyspark reading from excel files