在Material Design mdDialog documentation ,我注意到他们已经将范围(没有前缀美元符号)传递给底部附近的 DialogController
。
(function(angular, undefined){
"use strict";
angular
.module('demoApp', ['ngMaterial'])
.controller('AppCtrl', AppController);
function AppController($scope, $mdDialog) {
var alert;
$scope.showAlert = showAlert;
$scope.showDialog = showDialog;
$scope.items = [1, 2, 3];
// Internal method
function showAlert() {
alert = $mdDialog.alert({
title: 'Attention',
content: 'This is an example of how easy dialogs can be!',
ok: 'Close'
});
$mdDialog
.show( alert )
.finally(function() {
alert = undefined;
});
}
function showDialog($event) {
var parentEl = angular.element(document.body);
$mdDialog.show({
parent: parentEl,
targetEvent: $event,
template:
'<md-dialog aria-label="List dialog">' +
' <md-dialog-content>'+
' <md-list>'+
' <md-list-item ng-repeat="item in items">'+
' <p>Number {{item}}</p>' +
' '+
' </md-list-item></md-list>'+
' </md-dialog-content>' +
' <div class="md-actions">' +
' <md-button ng-click="closeDialog()" class="md-primary">' +
' Close Dialog' +
' </md-button>' +
' </div>' +
'</md-dialog>',
locals: {
items: $scope.items
},
controller: DialogController
});
function DialogController(scope, $mdDialog, items) {
scope.items = items;
scope.closeDialog = function() {
$mdDialog.hide();
}
}
}
})(angular);
我读到 $
是一种命名约定,也是确保变量不被覆盖的好方法。为什么此代码不遵循该约定?即在这种情况下,我们如何知道何时使用 $
,有什么意义?我相信在这种情况下,它一定不仅仅是命名约定,否则作者会选择使用 $scope
来保持一致性。
注意:我知道 $scope
和 scope
在链接函数中的区别,其中 scope
指向一组固定的参数。我不认为这就是为什么在这种情况下使用 scope
的原因,但如果我错了,请随时告诉我。
谢谢!
最佳答案
我认为文档在这里不一致 - 但同时是正确的。
这里的scope
和$scope
是一样的,不过我是看了源码才知道的。罪魁祸首在里面 InterimElement
其中 locals
由 options
扩展,后者又具有 scope
属性。
return showDone = compilePromise.then(function(compileData) {
angular.extend(compileData.locals, self.options);
element = compileData.link(options.scope);
我很确定将 $scope
作为 scope
访问只是偶然的,为了保持整洁,应该使用 $scope
引用 $injector
提供的值,例如在 Controller 中。
我已经提交了 a pull request修复不一致并编译a pen demonstrating the usage .
关于javascript - AngularJS — 将范围(不带 $)注入(inject) Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30117637/