javascript - 将逻辑移至 Angular 中的服务

标签 javascript angularjs

我最终在 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/

相关文章:

javascript - 从一开始就删除一个字符哈希/井号

javascript - leaflet.js 标记未显示

javascript - AngularJS/Javascript 拼接的奇怪行为

javascript - 返回 ion-item 的 ajax 数据循环

javascript - AngularJS : how to use ng-change in factories?

javascript - 将react-bootstrap复选框设置为取消选中状态

javascript - 浏览器端Dust.js

html - CSS:工具提示显示在列表滚动上与父级的距离

javascript - 你如何将 ng-repeat 值推送到 Controller ?

javascript - 使用angularjs根据文本字段输入隐藏div