我最终在 Controller 中发现了很多逻辑,但我意识到这些逻辑并不好。因此我想将其转移到服务中。
目前 Controller 接受来自 YouTube 或 Vimeo 的 URL。它检测网址中是否存在字符串“youtube”或“vimeo”,然后执行相应的操作。以下是当前驻留在 Controller 中的部分“逻辑”:
if url.indexOf("youtube") > -1 {
variable_1 = "Something";
variable_2 = "Something";
//do some more stuff
}
else {
variable_1 = "Something";
variable_2 = "Something";
//do some more stuff
}
$scope.task.items.push("I need to add things to this array too");
服务是可行的方法,但我的第一个问题是服务
还是工厂
?
这就是我正在研究的内容,但我不确定在服务完成后如何将 Controller 中存在的变量(variable_1 和variable_2)传递回 Controller 。
myApp.service('urlService', function() {
this.detectProvider = function() {
if url.indexOf("youtube") > -1 {
}
else {
}
//how can I push things to the $scope array here?
};
});
最佳答案
为您服务
myApp.service('urlService', function() {
this.detectProvider = function(url) {
arrayOfMyVars = new Array();
if url.indexOf("youtube") > -1 {
arrayOfMyVars.push("Something");
arrayOfMyVars.push("SomethingElse");
}
else {
arrayOfMyVars.push("Something");
arrayOfMyVars.push("SomethingElse");
}
//how can I push things to the $scope array here?
return arrayOfMyVars;
};
});
在你的 Controller 中
var res = urlService.detectProvider(url);
variable_1=res[0];
variable_2=res[1];
$scope.task.items.push('the thing you need to push'); // maybe res[2] and in your service you had another arrayOfMyVars.push('the thing you need to push')...
不要忘记将您的服务导入到 Controller 中;)
关于javascript - 将逻辑移至 Angular 中的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23998153/