视图不应该指定配置
In Angular, the template should never dictate configuration, which is inherently what people desire when they want to pass arguments to controllers from a template file. This becomes a slippery slope. If config settings are hard-coded in templates (such as by a directive or controller argument attribute), you can no longer re-use that template for anything but that single use. Soon you'll want to re-use that template, but with different config and now in order to do so you'll either be pre-processing the templates to inject variables before it gets passed to angular or using massive directives to spit out giant blocks of HTML so you re-use all of the controller HTML except for the wrapper div and it's arguments. For small projects it's no big deal. For something big (what angular excels at), it gets ugly quick.
替代方案:模块
This type of configuration is what modules were designed to handle. In many angular tutorials people have a single module for their entire application, but really the system is designed and fully supports many small modules each which wrap small pieces of the total application. Ideally, controllers, modules etc would be declared in separate files and stitched together in specific re-usable chunks. When your application is designed this way, you get a lot of re-use in addition to easy controller arguments.
The example below has 2 modules, re-using the same controller, but each with their own config settings. That config settings are passed in via dependency injection using module.value. This adheres to the angular way because we have the following: constructor dependency injection, reusable controller code, reusable controller templates (the controller div could easily be included with ng-include), easily unit-testable system without HTML, and lastly re-usable modules as the vehicle for stitching the pieces together.
这里有一个例子:
<!-- index.html -->
<div id="module1">
<div ng-controller="MyCtrl">
<div>{{foo}}</div>
</div>
</div>
<div id="module2">
<div ng-controller="MyCtrl">
<div>{{foo}}</div>
</div>
</div>
<script>
// part of this template, or a JS file designed to be used with this template
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById("module1"), ["module1"]);
angular.bootstrap(document.getElementById("module2"), ["module2"]);
});
</script>
<!-- scripts which will likely in be in their seperate files -->
<script>
// MyCtrl.js
var MyCtrl = function($scope, foo) {
$scope.foo = foo;
}
MyCtrl.$inject = ["$scope", "foo"];
// Module1.js
var module1 = angular.module('module1', []);
module1.value("foo", "fooValue1");
module1.controller("MyCtrl", MyCtrl);
// Module2.js file
var module2 = angular.module('module2', []);
module2.value("foo", "fooValue2");
module2.controller("MyCtrl", MyCtrl);
</script>
查看它的实际运行情况:jsFiddle。