您可以在没有控制器且没有隔离范围的情况下创建指令。在链接功能中,我有时会做这样的事情:
.directive('toggle', function ($parse) {
return {
/* We can't use an isolated scope in this directive, because it happens
* all the time that you need to put a toggle on an element that uses the scope:
* <span toggle="boolVar" ng-class="{active: boolVar}">{{someVar}}</span>
*
* Transclusion can be an option to make the {{someVar}} work,
* but the ng-class will use the isolated scope for this directive
* (if we'd use the isolated scope, which we don't)
*/
link: function (scope, $element, attrs) {
// use a $parse getter/setter, because toggle can contain a
// complicated expression
var getter = $parse(attrs.toggle);
var setter = getter.assign;
$element.on('click', function () {
scope.$apply(function () {
setter(scope, !getter(scope));
});
});
}
};
});
也许这个 $parse 技巧有助于您的命令设置......