AngularJS将String转换为引用$ scope中对象的Object/Array

0 javascript string implicit-conversion angularjs

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

<div ng-controller="myController">
    <ul>
      <li myDirective="model[1].list" >a lot more things will happen inside here</li>
    </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

控制器:

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

指示:

    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

                  */
             }
        }

    }]);
Run Code Online (Sandbox Code Playgroud)

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

非常感谢你,

Nik*_*los 7

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

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