从自己的事件中访问angular$scope
Getting access to angular $scope from own event
$I有一个自定义的javascript对象,它可以触发事件。我想访问事件处理程序中的angular$scope,但我在某个地方读到使用angular.element(…).scope()是不好的,因为它只用于测试。
我的另一个想法是在控制器中注册对象的句柄,但这不起作用(看起来像是设置了$scope.somevalue,但我认为$scope不是同一个对象)。
我在Stack Overflow上找到了许多类似问题的答案,但它们似乎都在使用指令。我只想在对象更新时从中获取一个值,并将其显示出来
以下是我尝试过的两种方法。
var myObj = GetMyObjInstance();
// Working, but apparently it's not good practise to call .scope() on an element.
myObj.onUpdated = function(){
console.log("myObj updated");
var v = myObj.getValue();
var controllerDiv = document.getElementById("controller");
var $scope = angular.element(controllerDiv).scope();
$scope.apply(function(){
$scope.someValue = v;
});
}
// Tried to do this, thinking i would get closure on the scope.
angular.module('myApp', []).controller('controller', function($scope){
myObj.onUpdated = function(){
console.log("myObj updated"); // Gets logged to console...
var v = myObj.getValue();
$scope.somevalue = v; // ... but somevalue does not get displayed.
$scope.apply(); // Error, says it's not a function, so maybe this is not the right object?.
}
});
使用AngularJS指令来处理事件和更新范围。
app.directive("xdEvent", function() {
return linkFn(scope, elem, attrs) {
elem.on("event", function(e) {
scope.$eval(attrs.xdEvent, {$event: e});
scope.$apply();
});
};
};
使用
<div xd-event="fn($event)"></div>
我认为使用服务而不是控制器是更好的做法。您可以使用注入器从外部javascript调用服务,如下线程中所述:从简单的js代码调用angularjs服务
如果从控制器访问这些变量仍然很重要,那么可以使用$watch告诉控制器在服务变量更改时更新自己。
希望得到帮助。
A+
相关文章:
- Angular$scope在模式窗口内不起作用
- 在将绑定应用于控制器之后,是否会发出Angular$scope事件
- Angular $scope更新、导航和 $scope.$apply() 后不绑定到视图
- 重复修改ng内Angular Scope内的对象
- 从Angular Scope中的Array中获取所有对象
- Angular$scope在更新时未将结果传递给父控制器
- Angular:$scope有效,但“;控制器为“;不触发ng更改事件
- 从自己的事件中访问angular$scope
- angular scope变量在动态创建的html中不起作用
- 无法访问Electron ipcRenderer内部实现的Angular$scope变量
- 指令中需要父 FormController 的 Angular (scope?) 问题
- 将异步 REST 调用 JSON 添加到 Angular $scope
- Issue With Angular $scope.Watch
- Angular$scope$注意(for in..)don'不起作用
- 在PageMod Firefox中获取Angular Scope
- Angular$scope$注意仅从表单(ng-model指令)更改的变量
- 有条件地信任angular scope变量中的html
- 使用Typescript的javascript函数中的Angular Scope
- Angular scope手表;在我的应用程序中不起作用
- 在初始加载时初始化Angular$scope