在我的应用程序中,我有两个几乎相同的控制很多功能都是一样的,所以我想把它们原型化.这是控制器#1:
c2gcontroller.js
angular.module('c2gyoApp') .controller('C2gCtrl',function($scope) { // some unique stuff $scope.Feeday = 59; ... // the identical functions $scope.getMinutes = function(minutes) { var duration = moment.duration(minutes,'m'); return duration.minutes(); }; ... });
和控制器#2:
c2gbcontroller.js
angular.module('c2gyoApp') .controller('C2gbCtrl',function($scope) { // some unique stuff $scope.Feeday = 89; ... // the identical functions $scope.getMinutes = function(minutes) { var duration = moment.duration(minutes,'m'); return duration.minutes(); }; ... });
我已经尝试将$scope.getMinutes放入工厂:
smfactory.js
angular.module('c2gyoApp') .factory('smfactory',function() { return { getHours: function(minutes) { var duration = moment.duration(minutes,'m'); return Math.ceil(duration.asHours() % 24); } }; });
我已经将smfactory注入c2gcontroller.js
c2gcontroller.js(尝试#1)
angular.module('c2gyoApp') .controller('C2gCtrl',function($scope,smfactory) { ... // the identical functions $scope.getHours = smfactory.getHours(minutes); ... });
这会产生一个错误,即未定义分钟
line 33 col 42 'minutes' is not defined.
所以我尝试过:
c2gcontroller.js(尝试#2)
angular.module('c2gyoApp') .controller('C2gCtrl',smfactory) { ... // the identical functions $scope.getMinutes = function(minutes) { return smfactory.getHours(minutes); }; ... });
这不会产生错误,但我的应用程序确实没有响应.基本上$scope.getMinutes现在不返回任何内容.
我已经阅读并观看了很多关于AngularJS服务,工厂,供应商的信息,但我不知道从哪里开始.原型c2gcontroller.js和c2gbcontroller.js的正确方法是什么?
解决方法
如何使用
angular.extend进行伪继承
/* define a "base" controller with shared functionality */ .controller('baseCtrl',['$scope',.. function($scope,...) { $scope.getMinutes = function(minutes) { var duration = moment.duration(minutes,'m'); return duration.minutes(); }; .controller('C2gCtrl',['$controller','$scope',... function($controller,$scope,...) { // copies the functionality from baseCtrl to this controller angular.extend(this,$controller('baseCtrl',{$scope: $scope})); // some unique stuff $scope.Feeday = 59; }) .controller('C2gbCtrl',{$scope: $scope})) // some unique stuff $scope.Feeday = 89; })