Tutorial Angularjs ng-controller


In Angularjs ng-controller is use for attached controller class to the view. This is key phase Angularjs support MVC (Model-View-Controller) framework.

Controller : ng-controller define controller class name, that calss include Business login of contoller. Contoller class has many function we can call that function on any evern as well.

syntex of ng-controller

<div ng-controller="{{expression}}">

{{expression}} : Name of a globally accessible constructor function


Here is a simple example of ng-controller. Adding, removing, clearing, and show value functions are declared in the controller.

 <!DOCTYPE html>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
     <script src="lib/angular/angular.js" type="text/javascript"></script>  
       angular.module("appMod", []);  
       function firstContoller() {  
         this.name = "Nikunj Kansara";  
         this.userinfo = [  
           {name:"Nikunj Kansara", address:"Ahmedabad India", phone:"989898", email:"nikunjkansara@gmail.com"},  
           {name:"Nikunj Kansara", address:"Ahmedabad India", phone:"989898", email:"nikunjkansara@gmail.com"}  
       firstContoller.prototype.showValue = function()  
       firstContoller.prototype.clear = function(content)  
         content.name = "";  
         content.address = "";  
         content.phone = "";  
         content.email = "";  
       firstContoller.prototype.remove = function(content)  
         var index = this.userinfo.indexOf(content);  
         this.userinfo.splice(index, 1);  
       firstContoller.prototype.add = function()  
         this.userinfo.push({name:"Nikunj Kansara", address:"Ahmedabad India", phone:"989898", email:"nikunjkansara@gmail.com"});  
     <div ng-app="appMod">  
       <div id="ctrl-as-exmpl" ng-controller="firstContoller as fc">  
         Name: <input type="text" ng-model="fc.name" />  
         [ <a href="" ng-click="fc.showValue()">show Value</a> ]<br/>  
         <ul ng-repeat="ui in fc.userinfo">  
           <li><label>Name:</label><input type="text" ng-model="ui.name"/></li>  
           <li><label>Address:</label><input type="text" ng-model="ui.address"/></li>  
           <li><label>phone:</label><input type="text" ng-model="ui.phone"/></li>  
           <li><label>email:</label><input type="text" ng-model="ui.email"/></li>  
           <li>[<a href="" ng-click="fc.clear(ui)">Clear</a>] | [<a href="" ng-click="fc.remove(ui)">Delete</a>]</li>  
         [<a href="" ng-click="fc.add()">Add User</a>]    

No comments

'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();