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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19741035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:40:09  来源:igfitidea点击:

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

javascriptstringangularjsimplicit-conversion

提问by user2947511

I created a directive in angular where its scope is not isolated

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

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

CONTROLLER:

控制器:

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

Directive:

指示:

    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

                  */
             }
        }

    }]);

one of the solution i used was this function i put this inside the directive and process the string assigned to the $attrs.myDirective it works well with "model.list" but with "model[2].list" it doesnt because its not built for it. How do I modify this function or are there better solutions for this problem...

我使用的解决方案之一是这个函数,我把它放在指令中,并处理分配给 $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]];
    }

Thank you very much,

非常感谢你,

回答by Nikos Paraskevopoulos

Use the $parseservice (docs) to get the value pointed to by the attribute:

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

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