mle*_*les 5 dependency-injection angularjs angularjs-service angularjs-factory angularjs-provider
在我的应用程序中,我有两个几乎相同的控制 很多功能都是一样的,所以我想把它们原型化.这是控制器#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();
};
...
});
Run Code Online (Sandbox Code Playgroud)
和控制器#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();
};
...
});
Run Code Online (Sandbox Code Playgroud)
我试过投入$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);
}
};
});
Run Code Online (Sandbox Code Playgroud)
我注入smfactory了c2gcontroller.js
c2gcontroller.js(尝试#1)
angular.module('c2gyoApp')
.controller('C2gCtrl', function($scope, smfactory) {
...
// the identical functions
$scope.getHours = smfactory.getHours(minutes);
...
});
Run Code Online (Sandbox Code Playgroud)
这会产生一个错误,即未定义分钟
line 33 col 42 'minutes' is not defined.
Run Code Online (Sandbox Code Playgroud)
所以我尝试过:
c2gcontroller.js(尝试#2)
angular.module('c2gyoApp')
.controller('C2gCtrl', function($scope, smfactory) {
...
// the identical functions
$scope.getMinutes = function(minutes) {
return smfactory.getHours(minutes);
};
...
});
Run Code Online (Sandbox Code Playgroud)
这不会产生错误,但我的应用程序确实没有响应.$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', ['$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 = 89;
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
750 次 |
| 最近记录: |