Angular 1.3 重大更改 - 范围设置但在 $apply 之前重置 [英] Angular 1.3 breaking changes - scope set but reset before $apply

查看:20
本文介绍了Angular 1.3 重大更改 - 范围设置但在 $apply 之前重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您需要传递构造函数,而不是像您那样传递其他一些函数.正如我在另一个答案中解释的那样,控制器不是通过调用 new 创建.它的创建方式如下:

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

问题在于没有使用返回值,而是使用了instance.在您的情况下,这意味着:

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

所以MainCtrl"最终成为空对象.你必须做你应该做的事情,传递构造函数:

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

这篇关于Angular 1.3 重大更改 - 范围设置但在 $apply 之前重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆