Angular 1.3 重大更改 - 范围设置但在 $apply 之前重置

Angular 1.3 breaking changes - scope set but reset before $apply

AngularJs 1.3.x,简单的控制器可以工作,但是一旦我使用 Typescript 和 Injection 重写它,它就会失败。如果我引用 1.2.x 它又开始工作了。

//This works in 1.3.x
scopeApp.controller('MyController', ['$scope', function ($scope) {
    $scope.username = 'World';
    $scope.sayHello = function () {
        $scope.greeting = 'Hello ' + $scope.username + '!';
    };
}]);

http://plnkr.co/edit/ssSuuZuGlrypemx3BU5r?p=preview

//This DOES NOT works in 1.3.x but does in 1.2.x
//The following code is produced via Typescript:
var MainFeature;
(function (MainFeature) {
    var MainCtrl = (function () {
        function MainCtrl($scope) {
            this.scope = $scope;
            this.name = "Sirar";
            this.message = '';
        }
        MainCtrl.prototype.SetMessage = function () {
            this.message = 'Hello' + this.name;
        };
        return MainCtrl;
    })();
    MainFeature.MainCtrl = MainCtrl;
})(MainFeature || (MainFeature = {}));

scopeApp.controller("MainCtrl", ["$scope", function ($scope) {
  return new MainFeature.MainCtrl($scope);
}]);

包含有价值信息但没有帮助的重大更改文档:

  1. https://docs.angularjs.org/guide/migration
  2. http://ng-learn.org/2014/06/Migration_Guide_from_1-2_to1-3/
  3. http://wildermuth.com/2014/11/11/Angular_1_3_and_Breaking_Change_for_Controllers

您需要传递构造函数,而不是像您那样传递其他函数。正如我在 中解释的那样,控制器不是通过调用 new 创建的。它的创建如下:

instance = Object.create(controllerPrototype);
...
return fn.apply(self, args);

要注意的是 return 值未被使用,而是 instance。在您的情况下,这意味着:

instance = Object.create({}); // should be MainCtrl.prototype
...
return fn.apply(self, args);

所以 "MainCtrl" 以空对象结束。你首先要做你应该做的,传递构造函数:

scopeApp.controller("MainCtrl", ["$scope", MainFeature.MainCtrl]);