我开始使用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函数及其使用,但因为我使用&#34;这个&#34;惯例,我没有$ scope变量。
如何调用$ apply方法?
答案 0 :(得分:16)
您当然可以使用带有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;
});
});
});