AngularJS将字符串转换为引用$scope中的对象的对象/数组

AngularJS Convert String to Object/Array that references the objects in the $scope

本文关键字:对象 数组 scope 字符串 转换 引用 AngularJS      更新时间:2023-09-26

我在 angular 中创建了一个指令,其范围不是孤立

<div ng-controller="myController">
    <ul>
      <li myDirective="model[1].list" >a lot more things will happen inside here</li>
    </ul>
</div>

控制器:

app.controller("myController",["$scope",function($scope){ 
$scope.model = [
       {
          list:[ "object1","object2","object3" ]
       },
       {
          list:[ "object4","object5","object6" ]
       },
       {
          list:[ "object7","object8","object9" ]
       }
    ]
}]);

命令:

    app.directive("myDirective",[function(){
    return {
         scope:true,
         controller:function($scope,$element,$attrs){
             /*
              How do I directly be able to manipulate from inside here what is assigned 
on the  $attrs.myDirective 
without ISOLATING the scope of the directive
                  */
             }
        }
    }]);

使用的解决方案之一是这个函数,我把它放在指令中并处理分配给 $attrs.myDirective 的字符串,它与"model.list"配合得很好但是对于"model[2].list",它不会,因为它不是为它而构建的。如何修改此功能或是否有更好的解决方案来解决此问题...

    $scope.rediks = function(string)
    {          
        var scope = $scope; 
        var scopeSplit = string.split('.');
        for (i = 0; i < scopeSplit.length - 1; i++)
        {
            scope = scope[scopeSplit[i]];
            if (scope == undefined) return;
        }
        return scope[scopeSplit[scopeSplit.length - 1]];
    }

谢谢

使用 $parse 服务 (docs) 获取属性指向的值:

controller: function($scope,$element,$attrs,$parse) {
    var value = $parse($attrs.myDirective)($scope);
    // for the above case, value = [ "object4","object5","object6" ]
}