[英]Call angular factory with pure javascript
I struggled to title this question but basically I'm just starting off with angular and am using ngMaterial. 我很难为这个问题命名,但是基本上我只是从angular开始,并且正在使用ngMaterial。 I have a toast created by using an angular factory 我有一个用角工厂创建的吐司
app.factory('notify', ['$mdToast', '$animate', function($mdToast, $animate) {
return {
showToast: function(msg) {
var toast = $mdToast.simple()
.content(msg)
.action('Close')
.highlightAction(false)
.position('top right');
$mdToast.show(toast).then(function() {
//
});
}
}
}]);
This works great if I have a button on the page that activates the toast however I have socket.io running as well with node monitoring redis for updates to pop up that notification. 如果我在页面上有一个按钮可以激活吐司,那么这很好用,但是我同时运行socket.io以及节点监视redis,以更新弹出该通知。 However I can't get it to work as I'm not quite sure how I can call that factory from within here 但是我不能使它正常工作,因为我不确定如何从这里调用该工厂
socket.on('notification.new', function (data) {
//call factory here to show toast
console.log(data);
});
I know if I have it on a controller I can do it by using 我知道我是否可以在控制器上使用它
angular.element().scope().showToast(data)
But I don't want to create an element just to house the controller to call the function. 但是我不想创建一个元素只是为了容纳控制器来调用函数。
What I did to solve this issue is I attached one of the functions inside the controller to the window
object. 解决此问题的方法是将控制器内部的功能之一附加到window
对象。 So something like 所以像
window.showToast = function(msg) {
var toast = $mdToast.simple()
.content(msg)
.action('Close')
.highlightAction(false)
.position('top right');
$mdToast.show(toast).then(function() {
//
});
Then, from within the socket io listener (or any raw javascript for that matter): 然后,从套接字io侦听器(或与此相关的任何原始javascript)中:
socket.on('notification.new', function (data) {
//call factory here to show toast
window.showToast(data); //or however you'd like
});
And that kind of worked for me. 这样对我有用。 I know this is not the best approach but since this question didn't have any answers at all I thought I'll post a workaround that at least does the job done. 我知道这不是最好的方法,但是由于这个问题根本没有任何答案,因此我认为我将发布一种变通办法,至少完成此工作。
You need to get hold of Angular services to use Angular in a raw Javascript. 您需要掌握Angular服务,才能在原始Javascript中使用Angular。
Refer to Call Angular JS from legacy code 请参阅从旧版代码调用Angular JS
- angular.element(domElement).scope() to get the current scope for the element angular.element(domElement).scope()获取元素的当前范围
- angular.element(domElement).injector() to get the current app injector angular.element(domElement).injector()获取当前的应用程序注入器
- angular.element(domElement).controller() to get a hold of the ng-controller instance. angular.element(domElement).controller()来获取ng-controller实例的所有权。
In your case use injector
service to get hold of your factory. 在您的情况下,请使用injector
服务来控制您的工厂。
Update 1 更新1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.