#reactjs #js #nodejs Nested Components (5 de N)

In the previous chapters (3 and 4) we have seen how to define components and them properties.

In today’s post we are going to take a look on how we can nest components and how to pass down the information. We are going to structure the project, and this sample, inside the ‘components’ folder and we are going to create a ‘Books’ folder where we will place our books related components.

Lets begin with the following component that will show a list of books and later on lets improve it.

Inside the render function we have define a books object that will use the map function to indicate how to render each book and will return a li element.

var React = require('react');
var BookList = React.createClass({
    getInitialState : function(){
        return {books : [
        {title:'Javascript: the definitive guide.',publisher:'O\'really',href:'http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527/ref=sr_1_3?s=books&ie=UTF8&qid=1454320709&sr=1-3&keywords=javascript'},
        {title:'Javascript: the good parts.',publisher:'O\'really',href:'http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ref=pd_bxgy_14_img_2?ie=UTF8&refRID=0D2QAFFJY18NZYGVCW8Q'}
        ]}
    },
    render: function(){
       var books = this.state.books.map((book,key)=><li key={key}> <a href={book.href}>{book.title} published by {book.publisher} </a></li>);
        return (
<div>

<ul>
                    {books}
                </ul>

            </div>

        );
    }
});
module.exports = BookList;

If we include it in our ‘mainComponent’, the result will show the list of predefined books.

var React = require('react');
var BookListItem = React.createClass({
    render: function(){
        return (
            <li>
                   <a href={this.props.book.href}> {this.props.book.title} published by {this.props.book.publisher}</a>
        </li>
    
        );
    }
});
module.exports = BookListItem;

As we can see its a really simple component but in the render function we are using props that are not defined inside the component.

Now, lets modify the components and lets pass it to the soon.


var React = require('react');
var BookListItem = require('./bookListItemComponent.js')
var BookList = React.createClass({
    getInitialState : function(){
        return {books : [
        {title:'Javascript: the definitive guide.',publisher:'O\'really',href:'http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527/ref=sr_1_3?s=books&ie=UTF8&qid=1454320709&sr=1-3&keywords=javascript'},
        {title:'Javascript: the good parts.',publisher:'O\'really',href:'http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ref=pd_bxgy_14_img_2?ie=UTF8&refRID=0D2QAFFJY18NZYGVCW8Q'}
        ]}
    },
    render: function(){
       var books = this.state.books.map((book,key)=>
        <BookListItem book={book}/>
       );
        return (
            <div>
                <ul>
                    {books}
                </ul>
            </div>
        );
    }
});
module.exports = BookList;

We had modified the function inside the map to use the child component and inside the tag we are defining the prop that will be used inside the component.

In the following chapter we are going to do a small break to talk about mongodb and later will pass to talk about Forms.

Hope the post helps.

#reactjs #nodejs #gulp #npm React Component properties and Life Cycle (4 of N)

In the previous chapter we created our first React component and explained some of the basic characteristics as render method, state and props.

Today’s post will let us to explain other properties of the components and the Component’s life cycle.

Properties:

PropTypes: admits an array where you can specify the property types and if they are required or not:

name : React.PropTypes.string.isRequired,

age : React.PropTypes.number

You can limit the values like using an enum:

gender: React.PropTypes.oneOf([‘male’,’female’]

You can define custom validations:

propName : function(props,propName,componentName){

}

A really interesting thing is the ability to indicate that the component can only have a nested children:

.propName : React.PropTypes.element

If you want to define the default values of the properties you should use:

getDefaultProps : function(){
return {name:'javi', age: 32};
}

Statics: it is an object where you can put statics method that can be used inside the component. (In a following post will see an example of this)

Mixins: This property is an array that let you put shared functions between components. (Cross-cutting concern)

Component’s life cycle:

There are some method that will help with the life cycle of our components:

componentWillMount:

This method is invoked before the first render occurs, in both server and client side.

componentDidMount:

This method occurs after the first rendering. You will be able to access the generad DOM. If you have multiple nested components the parent method will be executed after all nested soons method are ready.

It is highly recommended to use ajax calls in this method.

componentWillRecieveProps:

This method happens when new props arrives to the compoent. Just a reminder that the props are inmutable and the state is.

**In the next chapter will see a sample of nested components.

shouldComponentUpdate:

This method is called before the render when the state change.

If you want to avoid the render, you can return false in here and the render will not happen.

componentWillUpdate:

This method is invoked when the state change.

**You cant invoke setState here.

componentDidUpdate:

This method is invoked after the render has finished (only after first render)

componentWillUnmount:

This method is used to removed unneeded items and it is executed when the component is removed.

In the next post will see how to nest components and some of the concepts we had seen here.

 

#reactjs #nodejs #gulp #npm Creating our first Component and displaying it (3 of N)

In the previous chapters (1 and 2) we had defined the environment and the gulpfile.

In this one lets create or first component and explain how to display in our application.

Well, the first step will be to install React from npm

Npm install –save react

In our app folder we are going to create a Component folder where we will store every Component.

Lets call our first component “mainComponent.js”.

The structure for each component will be as follow:

var React = require('react');

var componentName = React.createClass(
                   {
                           render : function(){
                                                   return ();
                                            }
                    });

module.exports = componentName;

The first line will indicate that we want to use React and the last one will indicate that we are going to export our component.

The importance comes in the object as we are going to create it through React.createClass.

The createClass function will get an object that will have the properties and funcionality our component require, but it needs to fit a minimal structure. So its should have a render method:

The render method is in charge of painting our component in the HTML. Inside it we will use  JSX:


var Main = React.createClass({
 render: function(){
 return(
<div> Hello from React Component!</>
 );
 }
 });

As you can see in the sample we have a div tag and the text without any quotes, its the JSX magic.

The render method should not modify neither query the DOM, neither modify the properties of our component, and the method will be invoked once a change on the state of the component occurs.

Now lets differentiate between two of the characteristics of the components: the state and the properties.

The state is an object that has the mutable properties of our component.

The properties  are objects not mutable and shared between the different instance of our component.

 

You can define the initial state of the component using the “getInitialState” method. To use any characteristic of the state you should reference it through “this.state.” and to modify the value of the state it is required to use the setState function.

Lets create a first component:


var React = require('react');

var Main = React.createClass({
 modifyName : function(event){

this.setState({name:event.target.value});
 },
 getInitialState : function(){
 return {name : 'Javier'}
 },
 render: function(){
 return(
<div> Hello {this.state.name} from React Component!
 <input type='text' value={this.state.name} onChange = {this.modifyName}/></div>
);
 }
 });

module.exports = Main;

Its a really simple component, with a div and a textbox. The textbox value is stablished to the “name” characteristic of the state by using {}. We also had defined an initial value in the getInitialState, and we have a modifyName method bind to the Change event of the textbox.

Our main.js file, where we will get the previous component and will use React.render to display it on our app:

var React  = require('react');

var Main = require('./components/mainComponent.js');

React.render(<Main />,document.getElementById('app'));

And our index.html


<html>
<body>
<div id='app'></div>
<script src='/scripts/bundle.js' type="text/javascript"></script>
</body>

</html>

Now if we open the browser on localhost:7777

In the next chapter will carry on with more characteristics of the components.

#reactjs #nodejs #gulp #npm Defining the Gulpfile for our app

In the last chapter we defined very quickly the environment that we are going to use along this React series.

Today lets explain the npm packages that we will use and lets create the gulpFile.

I want to clarify that the things that we are going to do with GULP we can achieve it with NPM, webpack or grunt.

Well, firstly lets enumerate the npm packages and install them (npm install –save package-name):

  • Browserify: allow us to use require in our js code.
  • Reactify: in charge of transform JSX (specific of React) into js.
  • Vinyl-source-stream: In charge of convert files to vinyl streams, that are the affected format of GULP.
  • Gulp-concat: will allow us to concatenate files.
  • Gulp-open: will open an url in the specified browser..
  • Gulp-connect: its a dev server.

Once installed lets define the vars to be used in the gulpFile:


var open = require('gulp-open'); 

var browserify = require('browserify'); 
var reactify = require('reactify'); //transform jsx to js

var source = require('vinyl-source-stream'); 

var concat= require('gulp-concat');

Now lets define the rest of the file and in a while lets explain the different tasks:


var config={
    port:7777,
    devBaseUrl:'localhost',
    paths:{
        html:'./app/*.html',       
        js:'./src/**/*.js',
        dist:'./dist',
        serverJS : './server/main.js',
        css:['node_modules/bootstrap/dist/css/bootstrap.min.css',
             'node_modules/bootstrap/dist/css/bootstrap-theme.min.css',
             'node_modules/toastr/build/toastr.css']
    }
}


gulp.task('connect',function(){
    connect.server({
        root:['dist'],
        port:config.port,
        base:config.devBaseUrl,
        livereload:true
    })
});

gulp.task('open',['connect'],function(){
    gulp.src('dist/index.html')
        .pipe(open({uri:config.devBaseUrl + ':' + config.port + '/'}));
});

gulp.task('html',function(){
    gulp.src(config.paths.html)
        .pipe(gulp.dest(config.paths.dist))
    .pipe(connect.reload())
    
})
gulp.task('js',function(){
    browserify(config.paths.serverJS)
    .transform(reactify)
    .bundle()
    .on('error',console.error.bind(console))
    .pipe(source('bundle.js'))
    .pipe(gulp.dest(config.paths.dist + '/scripts'))
    .pipe(connect.reload());
    
})
gulp.task('css',function(){
    gulp.src(config.paths.css)
    .pipe(concat('bundle.css'))
    .pipe(gulp.dest(config.paths.dist + '/css'));
})
gulp.task('watch',function(){
    gulp.watch(config.paths.html,['html']);    
    gulp.watch(config.paths.js,['js']);
    gulp.watch(config.paths.css,['css']);

})
gulp.task('default',['html','js','css','open','watch'])

The “Connect” task will use gulp-connect to star the dev server and will use the following configuration:

  • root
  • port
  • base url
  • live reload

The “Open” depends on the fact that “connect” task had been executed, this means that the task will be executed only if the first run successfully. This task will open the file specified in the source and through a pipe will use the gulp-open the file.

The “HTML” task will be in charge of copying every html file from the source folder to the specified destination, furthermore, will reload the dev server.

The “JS” task will:

  • Use Browserify to convert our JS files.
  • Transform the files with React to convert JSX to JS.
  • Create a bundle.
  • If an error occurs show it in the console.
  • Copy the bundle file to an specific folder.
  • Reload the dev server.

The “CSS” task will concatenate every indicated css files through them folders and will copy the result to the destination directory.

The “Watch” task will be in charge of monitoring the HTML, JS and CSS files and if there are any changes will executed the associated task(s).

And the last one, the “Default” one, we are only going to define the dependencies required to be executed. As, its own name says its the default task, so if we just go to the command line and execute gulp, everything should start working.

In the next post we will start using REACT.

Hope you enjoy the post!

#reactjs #nodejs #gulp #npm First steps with React: defining the environment and Hello world!

This is the start of a new serie about REACT.

In this first post we will talk about the tools we are going to use to create the app:

 

  • Node JS:  JS runtime based on Chrome javascript kit.
  • NPM: Its the Node Package module where you can find a lot of 3rd party developers libraries.
  • VS Code: Its a cross platform  IDE created by Microsoft. There a lot of alternatives: Brackets, sublime, VS…
  • MongoDB: famous not relational Database.
  • Express: Express as dev server.
  • Gulp: As javascript Task runner.

Firstly, If you dont have them yet, lets get and install the tools.

Once ready, lets define the structure of our project under c:\projects\reactTutorial, and from the command line lets run “npm init”.

This command will create a file “packages.json” under our folder and will host information that we are going to fill while the command is running:

  • name
  • version
  • description
  •  entry point
  • git repository
  • author
  • license

Well, now its time to get a brief structure for the project, so lets create a couple of folder under our base folder called Server and App. In the first will host server components, and in the App folder the client files.

For this post and to go quickly to the Hello world sample, lets go in a rush through gulp, so lets install GULP from npm:

npm install –save gulp

Now, lets define the main.js for the server, a simple Index.html file an the gulpFile.js:

main.js: This server will be the express app and will be hosted on the Server folder:

var express = require('express');

var app = new express();

console.log('Starting');

var path = require('path');

app.get('/',function(req,res){
    res.sendFile( path.resolve('./app/index.html'))
})
   
    .listen(7777);

index.html: html file that will be hosted under App folder.

<html>
    <body>
        Hello world!!
    </body>
        
</html>

gulpFile.js: in the following post will explain about gulp.

var gulp = require(‘gulp’);
var LiveServer = require(‘gulp-live-server’);

gulp.task(‘live-server’,function(){
var server = new LiveServer(‘server/main.js’);
server.start();
})

Lastly, lets go back to the console and run the command gulp live-server, then we should go the our browser to localhost:7777 and here we are, our Hello world example.

In the following post, will describe information about Gulp and later on about React and Express.

#Angular Replication broadcast events using promises

If you have followed up my previous post, we were reviewing how to consume a Rest API from an Angular service using $http por sending our ajax request to the API, and we were using broadcast events to notify across the application.

There is one better way to consume the api using a promise with $q.

Lets make a quick sample:


alizan.factory('ProductService', ['$http', '$q', '$rootScope', function ($http, $q, $rootScope) {
var productService = {
getproduct: {},
products: [],
identity: 0,

GetAll: function () {
var path = 'api/product/GetAll';
var deferred = $q.defer();
var value = [];
$http.get(path).then(
function (response) {
response.data.forEach(function (val) {
value.push(val);
});
deferred.resolve(value);
});

function callPromise(promise, value) {
promise.$object = value;
return promise;
}
return callPromise(deferred.promise, value);

}
};
productService.GetAll();
return productService;
}
]);

With this approach we don’t need to suscribe to any events in other controllers, so to use them:


$scope.Products = ProductService.GetAll().$object;

And that’s all!

 

Hope you like the post.

Consuming a Rest Api from #Angularjs

In the previous post we were reviewing how to create a Web Api with Vs2013 and Dapper.

Today, we are going to review how to consume the rest Api from AngularJs.

Using a Service inside Angular

Despite in angular exists different ways to consume APIs, in this article we are going to use the Service Provider:

 

function ProductService($http, $rootScope) {
    var productService = {
        getproduct: {},
        products: [],
        identity: 0,

        AddProduct: function (product, caller) {
            $http.post("api/product/CreateProduct", product).success(function (data) {
                productService.getproduct = data;
                $rootScope.$broadcast('productAdded');
                productService.GetAll();
            });
        },
        UpdateProduct: function (product, caller) {

            $http.put("api/product/UpdateProduct", product).success(function (data) {
                productService.getproduct = data;
                $rootScope.$broadcast('productUpdated');
                productService.GetAll();

            });
        },
        DeleteProduct: function (id, caller) {
            $http.post("api/product/DeleteProduct", { id: id }).success(function (data) {
                $rootScope.$broadcast('productDeleted');
                productService.GetAll();
            });
        },
        GetById: function (id, caller) {
            $http.get("api/product/SearchById/" + id).success(function (data) {
                productService.getproduct = data;
                $rootScope.$broadcast('productget');
            });
        },
        GetAll: function ( caller) {

            $http.get("api/product/GetAll").success(function (data) {
                productService.products = data;
                $rootScope.$broadcast('productsupdated');
            });
        }
    };
    productService.GetAll();
    return productService;
}

Once defined the service, we should setup our application and the controller.

 
       alizan.factory('ProductService', ['$http', '$rootScope',  ProductService]);
       alizan.controller('ProductController', ['$scope', 'ProductService', ProductController]);
function ProductController($scope, ProductService) {
    $scope.Product = {
        Id:0,
        Name: '',
        Price: 0,
        Description:''
    }
    $scope.Products = [];
    $scope.FilterId = 0;
    $scope.Add = function () {
        ProductService.AddProduct($scope.Product);
    }
    $scope.Update = function () {
        ProductService.UpdateProduct($scope.Product);

    }
    $scope.Delete = function () {
        ProductService.DeleteProduct($scope.Product.Id);
    }
    $scope.GetById = function () {
        ProductService.GetById($scope.FilterId);
    }
    $scope.$on('productsupdated', function (res) {
        $scope.Products = ProductService.products;

    });
    $scope.$on('productUpdated', function (res) {
        $scope.Product = ProductService.getproduct;

    });
    $scope.$on('productAdded', function (res) {
        $scope.Product = ProductService.getproduct;

    });
    $scope.$on('productget', function (res) {
        $scope.Product = ProductService.getproduct;

    });
}

After configuring the service, the controller and the application, it’s the turn of define the View:

   <div ng-controller="ProductController">
        <ul>
            <li ng-repeat="product in Products">{{product.Name}}</li>
        </ul>
        Filter <input type="text" ng-model="FilterId" />
        <br />
        Name <input type="text" ng-model="Product.Name" />
        Price <input type="text" ng-model="Product.Price" />
        Description <input type="text" ng-model="Product.Description" />
        <input type="button" ng-click="Add()" value="Add" />
        <input type="button" ng-click="Update()" value="Update" />
        <input type="button" ng-click="Delete()" value="Delete" />
        <input type="button" ng-click="GetById()" value="Get" />
    </div>

In the next #Angularjs article, will review the differences between using Services, Factories and providers.

Hope you enjoy the post!

#UPDATED# Creating a WebApi using Dapper as ORM

Some time ago, I was reviewing several ORMs (in my old blog).

The ORM Choice

On this occasion I want to use Dapper which define a set of extension method to DbConnection that let you execute your SQL queries easily.

The main advantages of Dapper and things that I really like of it are

– Speed: It’s really fast to get the results from the database.

– Automapping: if you execute a query its Dapper is able to map to a DTO object and if you are using a create, update or delete query is able to map the parameters only passing the DTO.

– Multiplequeries: Dapper lets you to run multiple queries in one trip 🙂

Let’s Start

The first step will be to create a Web api project in VS2013.

api1

After that, we can download Dapper from GitHub, or add the reference from Nugget.

api2

 

Now, we need to create a class for each of the objects we want to map from the Database, so lets create a first example for this:


public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}

Furthermore, we are going to create a DAL class for managing the database operations:

public class ProductDal
    {
        private SqlConnection connection;

        public ProductDal()
        {
            connection = new SqlConnection(@"Data Source=.;Initial Catalog=Alizan;Integrated Security=true;MultipleActiveResultSets=true;");
        }

        public IEnumerable<Product> GetAll()
        {
            return connection.Query<Product>("SELECT ID,NAME,DESCRIPTION,PRICE FROM PRODUCT");
        }
        public Product GetById(int id)
        {
            return connection.Query<Product>(new CommandDefinition("SELECT ID,NAME,DESCRIPTION,PRICE FROM PRODUCT WHERE ID = @ID",
                new {Id = id})).FirstOrDefault();
        }
        public void Create(Product product)
        {
            product.Id =
                connection.ExecuteScalar<int>(new CommandDefinition(
                                    "INSERT INTO PRODUCT (NAME,DESCRIPTION,PRICE) VALUES(@NAME,@DESCRIPTION,@PRICE) SELECT SCOPE_IDENTITY()",
                                    product));

        }
        public void Update(Product product)
        {

            connection.ExecuteScalar(new CommandDefinition(
                                "UPDATE PRODUCT SET NAME =@NAME ,DESCRIPTION = @DESCRIPTION,PRICE=@PRICE WHERE ID=@ID",
                                product));
        }
        public void Delete(int id)
        {
            connection.ExecuteScalar(new CommandDefinition("DELETE PRODUCT WHERE ID=@ID", new{Id = id}));
        }
        public void Truncate()
        {
            connection.ExecuteScalar(new CommandDefinition("TRUNCATE TABLE PRODUCT"));
        }
    }

Now, its the moment to create our API controller to return the data to our clients:

 public class ProductController : ApiController
    {
        private ProductDal context;

        public ProductController()
        {
            context = new ProductDal();
        }
        [Route("api/Product/GetAll")]
        public IEnumerable<Product> GetAll()
        {
            return context.GetAll();
        }
        [HttpGet,Route("api/Product/SearchById/{id}")]
        public Product SearchById(int id)
        {
            return context.GetById(id);
        }

        [HttpPost,Route("api/Product/CreateProduct")]
        public Product CreateProduct(Product product)
        {
            context.Create(product);
            return product;
        }
        [HttpPut]
        public Product UpdateProduct(Product product)
        {
            context.Update(product);
            return product;
        }
         [HttpPost]
        public void DeleteProduct(Product product)
        {
            context.Delete(product.Id);
        }
    }

In the controller we have defined a set of classes for getting the data from our Database, and a controller for managing the information related to the class.

In the next post, I will explain how to consume from our Angular application.

Hope you enjoy the post!

 

Define Angular Directive(II)

After a chat with my friend Pedro about my first post in this blog related to defining Angular directives, he made me realize that it was a better way to avoid unnecessary scopes.

Starting

The first thing that we are going to do is to install Batarang a Chrome extension that let you debug your angular application and evaluate your objects.

In the previous post we had seen to use an Isolated Scope (indicated on the directive) to indicate which object are going to be the model of the directive.


angular.module('angularDirectiveSampleModule', [])
   .controller('Controller', ['$scope', function($scope) {
                         $scope.products=[];
                         $scope.products.push({ name: 'Book', price: 15.25 });
                         $scope.products.push({ name: 'Tablet', price: 185.95 });
               }])
   .directive('myProduct', function() {
      return {
              restrict: 'E',
              scope: {product: '=info'},
              templateUrl: 'my-product.html'
              };
});

The Isolated scope come defined on the scope attribute while defining the directive. For using this, we can use the following HTML


<my-product ng-repeat="product in products" info="product"></my-product>

If we evaluate this in Batarang
scopes1
We are going to see mores scopes than the neccesary.

The alternative

If we change our directive to the following (just removing the scope)

 angular.module('angularDirectiveSampleModule', [])
 .controller('Controller', ['$scope', function ($scope) {
 $scope.products = [];
 $scope.products.push({ name: 'Book', price: 15.25 });
 $scope.products.push({ name: 'Tablet', price: 185.95 });
 }])
 .directive('myProduct', function () {
 return {
 restrict: 'E',
 template: ' Name: {{product.name}} |Price: {{product.price}}'
 };
 }); 

And if we remove the reference to the isolated scope in the html

<my-product ng-repeat="product in products"></my-product>

We can see in batarang that we have a pretty solution
scopes2

I hope you like the post!

#AngularJS: Communicate controllers using a Service

Let’s imagine that you are creating a a simple shopping web site where you have the catalog of products an a shopping cart to be purchased.

When you choose a product in the catalog automatically should be added to the cart.

Thinking in AngularJS you will have a couple of controllers: a catalog controller that you will display the product of your shop, one more that will displayed the products to buy.

AngularJS have a mechanism for offer communication between different controllers using dependency injection. For info related to Services in Angular go to: Here

Let’s see in action!

Firstly, we are going to create the app, the service and the controllers in js:

   1: angular.module("app",[]).factory('productService',function($rootScope){

   2:   var productService ={

   3:     Products: [],

   4:     AddProduct : function(product,caller){

   5:       this.Products.push(product);

   6:       $rootScope.$broadcast('productAdded');

   7:  

   8:     },

   9:     RemoveProduct : function(product,caller){

  10:       var index = products.indexOf(product);

  11:       this.Products.splice(index,1);

  12:       $rootScope.$broadcast('productRemoved');

  13:  

  14:     }

  15:   };

  16:   return productService;

  17: })

  18: .controller('CatalogController', ['$scope','productService', function($scope,productService) {

  19:       $scope.Hello='Hey!, how are you?';

  20:       $scope.Products = productService.Products;

  21:       

  22:       $scope.Product={Name:'',Quantity:0};

  23:       $scope.AddProduct= function(){

  24:  

  25:         productService.AddProduct($scope.Product);

  26:         $scope.Product={Name:'',Quantity:0};

  27:       };

  28:       $scope.$on('productAdded', function () {

  29:             $scope.Products = productService.Products;

  30:         });

  31:         $scope.$on('productRemoved', function () {

  32:             $scope.Products = productService.Products;

  33:         });

  34:     }])

  35: .controller('ShoppingCartController', ['$scope','productService', function($scope,productService) {

  36:       $scope.Products = productService.Products;

  37:             $scope.$on('productAdded', function () {

  38:             $scope.Products = productService.Products;

  39:         });

  40:         $scope.$on('productRemoved', function () {

  41:             $scope.Products = productService.Products;

  42:         });

  43:       }]);

Now let’s create our markup

   1: <!DOCTYPE html>

   2: <html ng-app='app'>

   3:  

   4:   <head>

   5:     <script data-require="angular.js@1.3.0-rc2" data-semver="1.3.0-rc2" src="https://code.angularjs.org/1.3.0-rc.2/angular.js"></script>
   1:  

   2:     <link rel="stylesheet" href="style.css" />

   3:     <script src="app.js">

</script>

   6:   </head>

   7:  

   8:   <body>

   9:   <div ng-controller="CatalogController">

  10:     <h1>{{Hello}}</h1>

  11:     First Controller <br/>

  12:     Name: <input type="text" ng-model="Product.Name"/>

  13:     <br/>

  14:     Quantity: <input type="text" ng-model="Product.Quantity"/>

  15:     <br/>

  16:     <button ng-click="AddProduct()">Add</button>

  17:     <ul>

  18:       <li ng-repeat="product in Products">{{product.Name}}</li>

  19:     </ul>

  20:   </div>

  21:   

  22:     <div ng-controller="ShoppingCartController">

  23:   Second Controller

  24:     <ul>

  25:       <li ng-repeat="product in Products">{{product.Name}}</li>

  26:     </ul>

  27:   </div>

  28:     

  29:   </body>

  30:  

  31: </html>

 

Well, you can run this example here.

I hope you like the post!