我写了一个看起来像这样的指令:
在父html上:
<cl-sort-n-reverse flip-reverse="flipReverse()" set-key="setKey(key)" sort-key="sortKey" rev="reverse" key="body" title="Content"></cl-sort-n-reverse>
指令js中的:
.directive('clSortNReverse', function () {
return {
restrict: 'E',
scope:{
innerKey : '@key',
title : '@title',
inReverse: '=rev',
sortKey:'=',
flipReverse:'&',
setKey:'&'
},
transclude :true,
templateUrl:'../devhtml/common/sortNReverse.html',
link: function (scope, element, attrs) {
}
};
});
模板中的:
<span>
<div class="btn" ng-if="sortKey!=innerKey" data-ng-click="setKey({key:innerKey});">
{{title}}
</div>
<div class="btn" ng-if="sortKey==innerKey" data-ng-click="flipReverse();">
<b>{{title}}</b>
<i ng-if="inReverse===true" class="fa fa-caret-up"></i>
<i ng-show="inReverse===false" class="fa fa-caret-down"></i>
</div>
</span>
我真的希望能够在我的控制器中声明的一个对象中插入两个函数和范围级变量(如sortKey)和反向属性。我在这里找到的关于将对象添加到指令属性的答案都涉及一个更简单的情况,其中对象仅封装简单的字符串或数字。我很难理解如何定义选项对象以包含$ scope level stuff
答案 0 :(得分:1)
这是你的意思吗?
在您的控制器中:
$scope.sortReverseConfig = {
flipReverse: function() {...},
setKey: function(key) {...},
sortKey: '',
innerKey: $scope.body,
inReverse: $scope.reverse,
title: $scope.content
}
在你的HTML中:
<cl-sort-n-reverse config="sortReverseConfig"></cl-sort-n-reverse>
指令:
.directive('clSortNReverse', function () {
return {
restrict: 'E',
scope:{
config: '='
},
transclude :true,
templateUrl:'../devhtml/common/sortNReverse.html',
link: function (scope, element, attrs) {
}
};
});
指令模板:
<span>
<div class="btn" ng-if="config.sortKey != config.innerKey" data-ng-click="config.setKey({key:config.innerKey});">
{{config.title}}
</div>
<div class="btn" ng-if="config.sortKey == config.innerKey" data-ng-click="config.flipReverse();">
<b>{{config.title}}</b>
<i ng-if="config.inReverse === true" class="fa fa-caret-up"></i>
<i ng-show="config.inReverse === false" class="fa fa-caret-down"></i>
</div>
</span>