我试图用一些对谷歌,风格指南站点定义angulars最佳实践:https://google-styleguide.googlecode.com/svn/trunk/angularjs-google-style.htmlAngularJS最佳实践 - 风格指南
但此刻我的一些问题苦苦挣扎。在我使用这个样式指南之前,我有$scope
变量可用于在变量上执行$watch
。
app.controller('myController',['$scope', function($scope) {
$scope.$watch('myVariable', function(val) {
alert("I'm changed");
});
}]);
现在用我的新方法,我不知道如何处理这个?我还应该注入$scope
?因为我不使用$watch
时不需要注入$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]);
styleguide还建议使用原型。但是如果我不得不注入服务呢?在原型中使用服务的最佳方法是什么?
function myController(MyService) {
var vm = this;
vm.myService = MyService;
}
myController.prototype.callService = function() {
var vm = this;
vm.myService.doSomething();
}
这是正确的吗?或者我错过了什么,有没有一个地方可以找到更多关于这种角度编程风格的信息?
在我看来,它感觉更像自然的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();
}
但是,这感觉不对IMO ..
伟大的问题!对于你关于$ watch的问题,我想知道风格指南是否试图避免在控制器中调用$ watch,因为他们声明“控制器是类”。既然你知道数据在控制器中的变化,当控制器内部调用一个特定的方法时,是否会执行“$ watch”? – Pete
其实我想对一个指令内部变化的变量执行'$ watch'。我认为在方法内改变一个变量时不会有问题。我们称之为范围,无论如何都会得到更新。 – Dieterg
在指令中,您可以从链接,编译和控制器访问范围,因此在这些情况下可以访问$ watch。 – Pete