$ scope vs this in angular

时间:2015-01-07 06:01:21

标签: javascript angularjs

哪一个更好?为什么?

(function(){
  var app = angular.module('myApp', []);

  app.controller('MyController', function() {
    this.guy = obj1;
  });

  app.controller('AnotherController', function ($scope){
    $scope.guy = obj2;
  });

  var obj1 = {
    'name' : 'david',
    'title' : 'dude from obj1',
    'company' : 'AA',
    'doesIt' : 'this uses this'
  }, obj2 = {
    'name' : 'warren',
    'title' : 'dude from obj2',
    'company' : 'AA',
    'doesIt' : 'this uses scope'
  };
})();

我见过使用两者的教程。这是偏好吗?是否能够在html attr中使用控制器别名? $ scope的优点是什么?我正在寻找一个直截了当的答案。感谢。

1 个答案:

答案 0 :(得分:1)

controller as语法的主要优点 - 它使html更加清晰:

<div ng-contoller="parentController">
     <div ng-contoller="childController">
         <!-- you can't say exactly, where test located-->
         {{test}}  
     </div>
</div>

<div ng-contoller="parentController as parent">
     <div ng-contoller="childController as child">
         <!--it's clear where test-->
         {{parent.test}}  
     </div>
</div>

您也可以看到this