Monday, 22 June 2015

'this' in angularjs controller


This is your html:

<!DOCTYPE html>
<html>
  <head>
    <title>Templates</title>
    <script type="text/javascript" src="angular.js"></script>
    <script type="text/javascript" src="demo.js"></script>
  </head>
  <body ng-app="app" ng-controller="controller">
    <h1>{{1 + 1 + 1}}</h1>

    <input ng-init="numberb = 2" ng-model="numbera" type="number" placeholder="123">
    <input ng-model="numberb" type="number">
    {{numbera + numberb}}

    <button ng-click="vm.aa()">aa</button>
    <button ng-click="vm.bb()">bb</button>
    <button ng-click="xx()">xx</button>
  </body>
</html>


This is your controller:

angular.module('app',[]).controller("controller",function ($scope){
$scope.vm = this;
function aa(){
console.log("aaaaaa");
};

this.bb = function(){
console.log("bbbb");
};

$scope.xx = function(){
console.log("xxxxx");
};
});

"this" in controller is the instance of the controller.

function aa belong to the function : "function ($scope){}"

"function ($scope){}" is the constructor of your controller.

So, aa() function will not able to get called in able example.










No comments:

Post a comment