我正在尝试使用 google-styleguide 网站上定义的一些 Angular 最佳实践:https://google-styleguide.googlecode.com/svn/trunk/angularjs-google-style.html
但目前我正在努力解决一些问题。在我使用这个样式指南之前,我有 $scope
变量可以用来对一个变量执行 $watch
。
app.controller('myController',['$scope', function($scope) {
$scope.$watch('myVariable', function(val) {
alert("I'm changed");
});
}]);
现在用我的新方法我不知道如何处理这个?我还应该注入(inject) $scope
吗?因为当我不使用 $watch
时,我不必注入(inject) $scope
。
function myController($scope) {
var vm = this;
vm.myVariable = "aVariable";
vm.$watch('vm.myVariable', function(val) {
// error because $watch is undefined
});
//$scope.$watch - works
}
app.controller('myController',['$scope', myController]);
样式指南还建议使用原型(prototype)。但是,如果我必须注入(inject)服务怎么办?在原型(prototype)中使用服务的最佳方法是什么?
function myController(MyService) {
var vm = this;
vm.myService = MyService;
}
myController.prototype.callService = function() {
var vm = this;
vm.myService.doSomething();
}
这是正确的吗?还是我遗漏了什么,是否可以在某个地方找到有关这种 Angular 编程风格的更多信息?
在我看来,它更像是自然的 javascript,我想用这种方式来组织我的 AngularJS 应用程序。
提前致谢
更新
对于“服务”问题,我的想法如下:
function MyBaseController(AService, BService, CService) {
this.aService = AService;
this.bService = BService;
this.cService = CService;
}
function myController() {
var vm = this;
MyBaseController.apply(vm, arguments);
}
myController.prototype.doSomething() {
var vm = this;
this.aService.somethingElse();
}
但是我觉得这不对..
最佳答案
注入(inject) $scope 以访问 $watch 之类的东西是完全有效的,即使您使用“controller as”语法也是如此。例如:
JS
var MyController = function($scope) {
$scope.$watch('ctrl.someVar' function() {
...
});
this.someVar = 123;
}
MyController.$inject = ['$scope'];
HTML
<div ng-controller="MyController as ctrl">
....
</div>
您给出的第一个将服务注入(inject) Controller 的示例很好。对于继承示例,我会做这样的事情。
var BaseController = function(AService, BService) {
this.aService = AService;
this.bService = BService;
}
BaseController.prototype.doSomethingWithAAndB = function() {
...
}
var MyController = function(AService, BService, CService) {
BaseController.call(this, AService, BService);
this.cService = CService;
}
MyController.$inject = ['AService', 'BService', 'CService'];
//Note: you'll need to add a polyfill for Object.create if you want to support ES3.
MyController.prototype = Object.create(BaseController.prototype);
如果您发现在子 Controller 中指定所有参数太麻烦,您总是可以注入(inject) $injector
并将其传递给您的基本 Controller 。
关于javascript - AngularJS 最佳实践 - 风格指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22631541/