繁体   English   中英

访问AngularJS工厂方法/数组时出错

[英]Error accessing AngularJS factory methods/arrays

我将功能/对象划分为servicefactory方法,并将它们注入到我的控制器patentTab 我有一个用于标签面板的代码,该代码最初放置在有效的控制器patentTab中。

现在,我已将此代码放入工厂方法中,由于某种原因,内容未加载。 控制台日志未显示任何错误,并且当我单击相对选项卡时,已加载正确的URL,但内容没有更改。 我的阵列在工厂中有问题吗? 如果没有,原因是什么?

原始码

app.controller('patentTab', function($scope, $http){
    $scope.tabs = [{
    title: 'Patent Information',
    url: 'patent-info.htm'
}, {
    title: 'Cost Analysis',
    url: 'cost-analysis.htm'
}, {
    title: 'Renewal History',
    url: 'renewal-history.htm'
}];

$http.get('../json/patent-info.json').then(function(response){
    $scope.patentData = response.data.patentInfo;
})

$scope.currentTab = 'patent-info.htm';

$scope.onClickTab = function (tab) {
    $scope.currentTab = tab.url; //the tabs array is passed as a parameter from the view. The function returns the url property value from the array of objects.
}

$scope.isActiveTab = function(tabUrl) {
    return tabUrl == $scope.currentTab;
}
});

新代码(有问题)

 app.controller('patentCtrl', ['$scope', '$http', 'patentTabFactory', function($scope, $http, patentTabFactory) {

$http.get('http://localhost:8080/Sprint002b/restpatent/').then(function(response) {
    $scope.patents = response.data;
});

$scope.loadPatentItem = function(url) {
    $scope.patentItem = url;
}

$scope.tabs = patentTabFactory.tabs;
$scope.currentTab = patentTabFactory.currentTab;
$scope.onClickTab = patentTabFactory.onClickTab;
$scope.isActiveTab = patentTabFactory.isActiveTab;

}]);

app.factory('patentTabFactory', function() {

var factory = {};

factory.tabs = [{
    title: 'Patent Information',
    url: 'patent-info.htm'
}, {
    title: 'Cost Analysis',
    url: 'cost-analysis.htm'
}, {
    title: 'Renewal History',
    url: 'renewal-history.htm'
}];

factory.currentTab = 'patent-info.htm';

factory.onClickTab = function (tab) {
    factory.currentTab = tab.url; //the tabs array is passed as a parameter from the view. The function returns the url property value from the array of objects.
    console.log(tab.url);

}

factory.isActiveTab = function(tabUrl) {
    return tabUrl == factory.currentTab; //for styling purposes
}

return factory;

});

您没有从控制器调用factory.onClickTab()方法。 它应该像:

$scope.onClickTab = function(currentTab) {
    patentTabFactory.onClickTab(currentTab);
    $scope.currentTab = patentTabFactory.currentTab;
};

并且,对于isActiveTab ,例如:

$scope.isActiveTab = patentTabFactory.isActiveTab(currentTab);

这是我正在使用工厂的pl夫。 我所做的唯一更改是:1.将工厂文件放在应用程序脚本文件之前。 2.对工厂使用单独的声明,然后将其注入到应用程序中。

var factories = angular.module('plunker.factory', []);
factories.factory('patentTabFactory', function() {
// Factory bits
};

我已经在应用程序中注入了工厂。

var app = angular.module('plunker', ['plunker.factory']);

这是一个工作的小伙子。 朋克

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM