Javascript AngularJS:将target(类似于focus)设置为任何$scope属性

Javascript AngularJS:将target(类似于focus)设置为任何$scope属性,javascript,angularjs,angularjs-scope,Javascript,Angularjs,Angularjs Scope,我有一个布局与多个元素,能够获得目标。我一次只需要针对一个元素。 是否可以在$scope上定义一个函数,从模型接收对象(例如,属于发票的行项目),并告诉Angular在该模型视图所在的位置添加css类 如果我使用ng class指令,它将迫使我将ng class添加到html中的所有“targetable”元素中,并且每个元素都应该知道它是否是当前目标。我不想向每个可能的元素添加isTarget()函数,因为它会弄脏模型 例如: 这是html: <p>{{document.shipF

我有一个布局与多个元素,能够获得目标。我一次只需要针对一个元素。 是否可以在$scope上定义一个函数,从模型接收对象(例如,属于发票的行项目),并告诉Angular在该模型视图所在的位置添加css类

如果我使用ng class指令,它将迫使我将ng class添加到html中的所有“targetable”元素中,并且每个元素都应该知道它是否是当前目标。我不想向每个可能的元素添加isTarget()函数,因为它会弄脏模型

例如: 这是html:

<p>{{document.shipFrom}}</p>
<p>{{document.shipTo}}</p>
<ul>
    <li ng-repeat="item in document.items">{{item.description}}</li>
</ul>
是否有方法定义$scope.setTarget($scope.document.items[0]),以便在元素中添加“on target”类?请注意,所有文档属性(项目和shipFrom/To)都可以获得目标

编辑:已解决 我在指令的链接函数中找到了一种获取模型属性值的方法。如果我使用该服务,那么我可以通过实例化一个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>   

如果您不想向每个可能的项添加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>
  • {{{item.description}

  • 谢谢,但我找到了一种方法,可以将target应用到模型中的所有元素,而不仅仅是项目,而不需要定义ng click和ng class条件。请参阅我更新的问题。谢谢,但我找到了一种方法,可以将target应用于模型中的所有元素,而不仅仅是项,而无需定义ng click和ng类条件。请参阅我的最新问题。
    isTarget: function(item){
      return this.target === item;
    }
    
    <li ng-repeat="item in document.items" ng-class="{'on-target': document.isTarget(item)}">{{item.description}}</li>