AngularJS使用$ apply而没有$ scope

马特奥·维莱尼克(Mateo Velenik)

我开始使用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>

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

this.myModel=someOtherObjectFromAForeignSource;

...并且输入控件内的值不变。我了解了$ apply函数及其用法,但是由于我使用了“ this”约定,因此我没有$ scope变量。

如何调用$ apply方法?

布罗科

当然,您仍然可以将$ scope与controller as语法一起使用没有问题。

其实这是你将如何处理事件($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;
    });
  });
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在AngularJS中使用$ scope。$ watch和$ scope。$ apply?

AngularJS $ scope。$ apply()困境

AngularJS $ scope。$ apply与$ q

AngularJS:在具有自己的 $scope 的模态中使用 Ctrl $scope

AngularJS $scope 没有显示价值

AngularJS-使用$ http时是否需要$ scope。$ apply

如何使用AngularJS $ scope?

在没有$ scope的情况下创建指令AngularJS

AngularJS-TypeError:对象#<Scope>没有方法'path'

没有$ scope和额外ModalController的AngularJs UI Modal(解析)

没有$ scope,模型不会改变。$ apply

ng-show对$ scope.apply没有反应

angularjs $ scope.apply()动态输入

使用$ scope。$ apply()的最佳实践;甚至$ scope在带有Angular Component的非Angular内容中

角$ scope在更新,导航和$ scope之后没有绑定到视图。$ apply()

带有 $compile 的 AngularJS 组件丢失了 $scope

AngularJS:从带有组件的$ scope迁移

.scope() 在 AngularJS 中有什么用?

$ scope。$ apply()有什么作用?

如何使用“ controller as”语法调用$ scope。$ apply()

即使使用 $apply 后 $scope 也不会更新

在function($ scope)旁边没有['$ scope'

是否有使用AngularJS指令WHITOUT $ scope的动态html元素?

没有Angularjs中的$ scope,作用域对象不会改变

没有$ scope,如何在Promise.all()中更新AngularJS(1.7.x)中的DOM?

在编辑对象时了解angularjs $ apply和$ scope

AngularJs scope.apply似乎破坏了autcomplete jQuery UI

AngularJS-为什么$ scope。$ apply影响其他范围

$ watch()没有更新$ scope