AngularJS使用$ apply而不使用$ scope

Mat*_*nik 8 javascript angularjs

我开始使用AngularJS,我接受了用这个编写控制器的约定,而不是使用$ scope.所以我的控制器看起来像这样:

myApp.controller("SomeController", function(){
    this.myModel={id:-1, name:"empty"};
});

<div ng-controller="SomeController as ctrl">
    <input type="text" ng-model="ctrl.myModel.name" />
</div>
Run Code Online (Sandbox Code Playgroud)

现在,我以这样的方式更改了控制器中的myModel对象:

this.myModel=someOtherObjectFromAForeignSource;
Run Code Online (Sandbox Code Playgroud)

...并且输入控件内的值不会改变.我读到了$ apply函数及其使用,但由于我使用"this"约定,我没有$ scope变量.

如何调用$ apply方法?

Bro*_*cco 17

你当然可以使用带有controller as语法的$ scope 而没有任何问题.

其实这是你将如何处理事件($on,$broadcast,$emit)只是把它注射到你的控制器:

app.controller('MyCtrl', function($scope){
   //set your properties/methods as you are
   this.message = 'foo';
   this.yell = function(){
     this.message = this.message.toUpperCase() + '!!!';
   };

  var vm = this;
  //and use $apply as needed
  somethingOutsideOfAngular(function(value){
    $scope.$apply(function(){
      vm.message = value;
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 这肯定是使用`controllerAs`语法的限制,因为你必须注入并调用`$ scope`,如答案所示 (3认同)