我有一个包含多个元素的布局,可以获得目标。我当时只需要定位一个元素。 是否可以在$ scope上定义一个从模型接收对象的函数(例如属于发票的行项),并告诉Angular在该模型的视图所在的位置添加一个css类?
如果我使用ng-class指令,它将迫使我将ng-class添加到html中的所有“可定位”元素,并且每个元素应该知道它是否是当前目标。我不想为每个可能的元素添加一个isTarget()函数,因为它会弄脏模型。
实施例: 这是html:
<p>{{document.shipFrom}}</p>
<p>{{document.shipTo}}</p>
<ul>
<li ng-repeat="item in document.items">{{item.description}}</li>
</ul>
这是控制器:
angular.module('myApp').controller('DocumentCtrl', function($scope){
$scope.document = {
shipFrom: 'Origin',
shipTo: 'Destination',
items: [
{description:'item1'},
{description:'item2'}
]
};
})
有没有办法定义$ scope.setTarget($ scope.document.items [0]),以便它为元素添加一个“on-target”类?请注意,所有文档属性(项目和shipFrom / To)都可以获得目标。
我找到了一种在指令的链接函数中获取模型属性值的方法。如果我使用$parse服务,那么我只需通过实例化一个getter函数来评估附加到指令的模型属性:
link: function postLink ($scope, $iElement, $iAttrs) {
var valueGetter = $parse($iAttrs.ngModel);
//Then, I can subscribe the directive to a custom event:
$scope.$on('set.target', function (event, elem) {
$iElement.removeClass('on-target alert-info');
//Now it gets the actual value of the model related to the directive
var value = valueGetter($scope);
//If both the model and the event's value are the same, then focus the element.
if (value == elem) {
$iElement.addClass('on-target alert-info');
$scope.setTarget(valueName, elem);
$scope.$apply();
}
return;
});
}//end link function
当我需要某些东西从控制器获得目标时,我只需$scope.$broadcast('set.target', $scope.document.shipFrom)
答案 0 :(得分:0)
HTML部分:
<p>{{document.shipFrom}}</p>
<p>{{document.shipTo}}</p>
<ul>
<li ng-repeat="item in document.items" ng-click="setTarget(item.description)" ng-class="{'active' : selectedTarget == item.description}">{{item.description}}</li>
</ul>
控制器:
$scope.document = {
shipFrom: 'Origin',
shipTo: 'Destination',
items: [
{description:'item1'},
{description:'item2'}
]
};
$scope.selectedTarget = '';
$scope.setTarget = function(data) {
$scope.selectedTarget = data;
};
答案 1 :(得分:0)
如果您不想为每个可能的项添加isTarget()函数,可以在文档上添加isTarget方法。
isTarget: function(item){
return this.target === item;
}
并将html更改为
<li ng-repeat="item in document.items" ng-class="{'on-target': document.isTarget(item)}">{{item.description}}</li>