我想你可以粗略地总结一下指令是什么“将一些功能封装到一个可以放到任何页面的小部件中的东西”,但除此之外还有更多。指令是通过创建新标签来扩展HTML的一种方式,允许您编写更多表现性标记。例如,您不必编写<div>
和一堆<li>
标签来创建评级控制,而是可以将其包装为新的<rating>
标签。或者,而不是大量的<div>
s和<span>
S和诸如此类的东西来创建一个标签式界面,您可以实现一对指令,也就是说,<tab>
和<tab-page>
,并使用它们像这样:
<tab>
<tab-page title="Tab 1"> tab content goes here </tab-page>
<tab-page title="Tab 2"> tab content goes here </tab-page>
</tab>
这是真正的指令的力量,增强HTML。这并不意味着你只应该创建“通用”指令;你可以也应该制作特定于你的应用程序的组件。所以,回到你的问题,你可以实现一个<loggedinuser>
标签来显示登录用户的名称,而不需要控制器提供信息。但是你绝对不应该依赖全局变量。该角的方式做这将是使用一种服务来存储这些信息,并将其注入指令:
app.controller('MainCtrl', function($scope, userInfo) {
$scope.logIn = function() {
userInfo.logIn('Walter White');
};
$scope.logOut = function() {
userInfo.logOut();
};
});
app.service('userInfo', function() {
this.username = ''
this.logIn = function(username) {
this.username = username;
};
this.logOut = function() {
this.username = '';
};
});
app.directive('loggedinUser', function(userInfo) {
return {
restrict: 'E',
scope: true,
template: '<h1>{{ userInfo.username }}</h1>',
controller: function($scope) {
$scope.userInfo = userInfo;
}
};
});
Plunker here。
如果你想开始创建强大的,可重用的指令,那么Angular dev guide on directives是一个必须去的地方。
不要在您的指令中创建一个独立的作用域,并在传递给您的指令的“链接”函数的作用域中查找所需的变量。或者如果您创建了一个独立的作用域,然后在父作用域中查找这些变量。 – akonsu