我开始使用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] 删除。
我来说两句