从Controller确定controllerAs语法

时间:2015-12-23 18:07:18

标签: angularjs

ng-controller指令有两种实例化控制器的方法。 Vanilla和controller as语法。控制器如何确定调用它的方式并相应地调整其行为?

例如:

<div ng-controller="myController" >
   <p> {{message}} World </p>
</div>

<div ng-controller="myController as myVm">
   <p> {{myVm.message}} World </p>
</div>

<div ng-controller="myController as otherVm">
   <p> {{otherVm.message}} World </p>
</div>

如何在我的控制器中完成这项工作?

angular.module("myApp").controller("myController", function($scope) {

    function usesClassSyntax() {
        //what do i put here?
        return true/false
    };

    if (usesClassSyntax()) {
         var vm = this;
    } else {
         var vm = $scope;
    };

    vm.message = "Hello";
});

1 个答案:

答案 0 :(得分:3)

通过使用控制器作为语法,我们只需在我们的范围内创建一个新变量..

angular.module("myApp").controller("myController", function($scope) {

  function usesClassSyntax() {
    //i think this will help
    if (typeof $scope.myVm != 'undefined')
      return true;
    else
      return false
  };

  if (usesClassSyntax()) {
    var vm = this;
  } else {
    var vm = $scope;
  };

  vm.message = "Hello";
});