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



我将函数/对象分为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);

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

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

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

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

这是一个工作机会。普伦克·

最新更新