Die*_*erg 6 javascript code-organization prototypal-inheritance angularjs
我正在尝试使用google-styleguide网站上定义的一些角度最佳做法: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");
});
}]);
Run Code Online (Sandbox Code Playgroud)
现在用我的新方法我不知道如何处理这个问题?我还应该注射$scope吗?因为我$scope不使用时不需要注射$watch.
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]);
Run Code Online (Sandbox Code Playgroud)
风格指南还建议使用原型.但是,如果我必须注入服务怎么办?在原型中使用服务的最佳方法是什么?
function myController(MyService) {
var vm = this;
vm.myService = MyService;
}
myController.prototype.callService = function() {
var vm = this;
vm.myService.doSomething();
}
Run Code Online (Sandbox Code Playgroud)
它是否正确?或者我错过了什么,是否有一个地方可以找到关于这种角度编程风格的更多信息?
在我看来,感觉更像是自然的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();
}
Run Code Online (Sandbox Code Playgroud)
但这感觉不对..
即使你使用"控制器为"语法,注入$ scope来访问诸如$ watch之类的东西也是完全有效的.例如:
JS
var MyController = function($scope) {
$scope.$watch('ctrl.someVar' function() {
...
});
this.someVar = 123;
}
MyController.$inject = ['$scope'];
Run Code Online (Sandbox Code Playgroud)
HTML
<div ng-controller="MyController as ctrl">
....
</div>
Run Code Online (Sandbox Code Playgroud)
您给控制器注入服务的第一个例子很好.对于继承示例,我会做这样的事情.
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);
Run Code Online (Sandbox Code Playgroud)
如果您发现在子控制器中指定所有参数太麻烦,您可以随时注入$injector并将其传递给基本控制器.
| 归档时间: |
|
| 查看次数: |
3027 次 |
| 最近记录: |