AngularJS:将目标(类似于焦点)设置为任何$scope属性

AngularJS: set target (similar to focus) to any $scope property

本文关键字:设置 任何 属性 scope 焦点 目标 类似于 AngularJS      更新时间:2023-09-26

我有一个包含多个元素的布局,这些元素能够获得目标。我一次只需要定位一个元素。是否可以在$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"类?请注意,所有文档属性(物料和发货自/收件人)都可以获得目标。

编辑:已解决

我找到了一种在指令的链接函数中获取模型属性值的方法。如果我使用 $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)

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;  
};

演示

如果你不想为每个可能的项添加一个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>