0

I am having trouble converting some Angular code. Currently, it is using Angular's $http service to get data from another file and display it on the page. I want it to still do this but with vm instead of $scope. Here's an example of my vain attempts to do this:

HTML

<h1>{{vm.welcome}}</h1>

Javascript

var app = angular.module('myApp', []);
app.controller('myCtrl', function() {
   $http.get("welcome.htm")
   .then(function(response) {
      var vm = this;
      vm.welcome = response.data;
   });
});

Also, I originally got this code from w3schools' Angular tutorial.

Hudson Taylor
  • 1,142
  • 2
  • 10
  • 30

1 Answers1

3

Add var vm = this; outside of the promise and inside of the controller.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($http) {
    var vm = this;
    $http.get("welcome.htm")
        .then(function(response) {
            vm.welcome = response.data;
        });
});

in the html use controller as reference the controller

<div ng-controller="myCtrl as vm"> 
   <h1>{{vm.welcome}}</h1>
</div>

refer this for get more detail about how this work in controller

Community
  • 1
  • 1
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80