AngularJS使用$ apply而不使用$ scope [英] AngularJS using $apply without $scope

查看:88
本文介绍了AngularJS使用$ apply而不使用$ scope的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I started working with AngularJS and I embraced the convention for writing controllers with this, not with $scope. So my controllers look like this:

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>

现在,我改变了控制器中的myModel对象,如下所示:

Now, I changed the myModel object in the controller in a way like this:

this.myModel=someOtherObjectFromAForeignSource;

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

... and the value inside the input control doesn't change. I read about the $apply function and it's use but since i use the "this" convention, I don't have a $scope variable.

我如何调用$ apply方法?

How do I call the $apply method?

推荐答案

你当然可以将$ scope与控制器一起用作语法没有问题。

You can certainly still use $scope with the controller as syntax with no issue.

事实上,这就是你如何处理事件( $ on $ broadcast $ emit )只需将其注入您的控制器:

In fact that is how you would handle events ($on, $broadcast, $emit) just inject it into your controller:

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

这篇关于AngularJS使用$ apply而不使用$ scope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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