angular ng-bind using path from string

angular ng-bind using path from string

本文关键字:from string path using ng-bind angular      更新时间:2023-09-26

编辑:问题很简单
绑定路径是字符串

我想从字符串中绑定一个值(字符串是值的路径)

<div ng-init="bigP = 'user.address.street'">
     <div class="whatever" ng-bind="data.bigP"></div>
     OR
     <div class="whatever">{{data.bigP}}</div>
</div>

我想要的数据是data.user.address.street。非常重要的是,结果将是{{data.user.address.street}}ng-bind="data.user.address.street"之类的东西,因为无限递归结构和我需要精确的数据绑定来处理脚本的其余部分

您可以通过将string更改为列表来使其工作:

<div ng-init="bigP = ['user','address','street']">
     <div class="whatever" ng-bind="data[bigP[0]][bigP[1]][bigP[2]]"></div>
     OR
     <div class="whatever">{{data[bigP[0]][bigP[1]][bigP[2]]}}</div>
</div>

这里有一个小提琴

答案:

当你有:

<script>
$scope.user.address.street = '5th Ave';
</script>

HTML中有:

<div class="whatever" data-path='user.address.street'>{{user.address.street}}</div>



用例:NG-REPEAT,内联编辑器等,无论什么原因,使用string path更改$scope中的值:

<script>
$parse('user.address.street').assign($scope,'I.Am.New.Value');
$scope.$apply()
</script>

谢谢