Sunday, 2 April 2017

How to use Controller using alias ?


USING CONTROLLER WITHOUT ALIAS 
JS
app.controller("controller1", function ($scope) {
    $scope.message = "Hello World";
});

HTML
<h1 ng-controller="controller1">{{ message }}</h1>


USING CONTROLLER WITH ALIAS
JS
app.controller("controller1", function () {
    this.message = "Hello World";
});

HTML
<h1 ng-controller="controller1 as c1">{{ c1.message }}</h1>


Common problem occurred using Alias (Unavailability of this variable inside inner funtions)
app.controller("controller1", function ($http) {
   $http.get("MyService/GetEmployee").then( function(response) {
      this.empData = response.data;
   })
});


Solution (Use another variable and assign this object outside the inner function and use it)

app.controller("controller1", function ($http) {
   var vm = this;
   $http.get("MyService/GetEmployee").then( function(response) {
      vm.empData = response.data;
   })
});

No comments:

Post a Comment

Note: only a member of this blog may post a comment.