我将我的函数/对象划分为service
和factory
方法,并将它们注入我的控制器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;
});
答案 0 :(得分:1)
您没有从控制器调用factory.onClickTab()
方法。
应该是这样的:
$scope.onClickTab = function(currentTab) {
patentTabFactory.onClickTab(currentTab);
$scope.currentTab = patentTabFactory.currentTab;
};
,对于isActiveTab
,赞:
$scope.isActiveTab = patentTabFactory.isActiveTab(currentTab);
答案 1 :(得分:0)
这是一个我正在使用工厂的掠夺者。我所做的唯一改变是: 1.将工厂文件放在应用程序脚本文件之前。 2.对工厂使用单独的声明,然后将其注入应用程序。
var factories = angular.module('plunker.factory', []);
factories.factory('patentTabFactory', function() {
// Factory bits
};
我在应用程序中注入了工厂。
var app = angular.module('plunker', ['plunker.factory']);
这是一个工作的掠夺者。 PlunkR