控制器使用$ scope?定制服务使用这个?

时间:2017-01-07 05:02:25

标签: angularjs

我在Controller中发现,我们使用$ scope,这里是链接(http://www.w3schools.com/angular/tryit.asp?filename=try_ng_controller)。 我将$ scope改为this,它无法工作。

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

但是,我发现在Service中,我们使用了这个,这里是链接(http://www.w3schools.com/angular/tryit.asp?filename=try_ng_services_custom)。 在hexafy服务中,我将其更改为$ scope,它无法正常工作。

<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>

我的上述摘要是否正确?如果没有,考虑各种可能的情况应该是正确的总结。

1 个答案:

答案 0 :(得分:0)

您也可以在控制器中使用而非 $ scope 。他们引入了 controller as 语法(来自Angular 1.2)。您可以将数据附加到(此处控制器保存数据)。但在内部它只会附加到$ scope,但您不必手动附加它。它必须像这样在html中声明,控制器被声明为 main ,所以我们必须使用 main 来引用html中的数据。

<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.
});