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

孤者浪人 提交于 2019-12-12 01:54:50

问题


AngularJs 1.3.x, simple controller works but as soon as I re-write it using Typescript and Injection, it fails. If I reference 1.2.x it starts working again.

//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);
}]);

Breaking changes docs that have valuable information but didn't help:

  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

回答1:


You need to pass the constructor function, not some other function like you did. As I explained in another answer the controller is not created by calling new. It's created as follows:

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

The catch is that the return value is not used, but the instance. In your case this would mean:

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

So "MainCtrl" ends up as empty object. You have to do what you should have done in the first place, pass the constructor:

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


来源:https://stackoverflow.com/questions/27915321/angular-1-3-breaking-changes-scope-set-but-reset-before-apply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!