-1

I found in Controller, we use $scope, here is the link (http://www.w3schools.com/angular/tryit.asp?filename=try_ng_controller). I change $scope to this, it cannot work.

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});
</script>

However, I found in Service, we use this, here is the link (http://www.w3schools.com/angular/tryit.asp?filename=try_ng_services_custom). In hexafy service, I change this to $scope, it cannot work.

<script>
var app = angular.module('myApp', []);

app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});
app.controller('myCtrl', function($scope, hexafy) {
  $scope.hex = hexafy.myFunc(255);
});
</script>

Does my above summary correct? If not, what should be correct summary considering all kinds of possible.

AngularJS
  • 27
  • 6

1 Answers1

0

You can use this instead of $scope in controller as well. They have brought in controller as syntax(from Angular 1.2). You can attach data to this(Here controller holds the data). But internally it will be attached to $scope only, but you don't have to attach it manually. It has to be declared in html like this , controller is declared as main , so we have to refer to data in html using main.

<div ng-controller="MainCtrl as main">
   {{ main.title }}
</div>

app.controller('MainCtrl', function ($scope) {
  this.title = 'Some title'; 
  console.log("Title" + $scope.main.title); // It will print some title in the console.
});
Sasank Sunkavalli
  • 3,864
  • 5
  • 31
  • 55