将范围名称更新为指令

时间:2013-09-25 15:36:05

标签: javascript angularjs angularjs-directive

我有一个指令,该属性包含一个范围名称,我希望在指令中设置某些内容时更新该范围。

<div data-my-directive data-scope-var-to-update="my_scope_variable"></div>



.directive('myDirective', function($rootScope){
        return function(scope, element, attrs){

            var scope_var_name = attrs.scopeVarToUpdate;

            scope[scope_var_name] = 'This message was updated from the directive';
        }
    })

只有当范围变量不包含任何点符号时,上面允许我做我想做的事。

我的问题是如何修改上述内容以满足包含点符号的范围变量,例如$ scope.a.b?

<div data-my-directive data-scope-var-to-update="a.b"></div>

上面的想法是传入任何范围变量名,并在完成它的工作后从指令更新它,这意味着父控制器应该可以访问新的赋值。

2 个答案:

答案 0 :(得分:1)

您使用scope.$eval(attrs.scopeVarToUpdate)

.directive('myDirective', function(){
    return function(scope, element, attrs){
        scope.$eval(attrs.scopeVarToUpdate) = 'This message was updated from the directive';
    }
})

或者使用具有双向绑定的隔离范围,不要担心任何问题。 隔离范围版本:

.directive('myDirective', function(){
    return{
      scope:{scopeVarToUpdate:'='},
      link: function(scope, element, attrs){
        scope.scopeVarToUpdate = 'This message was updated from the directive';
      }
    }
})

答案 1 :(得分:1)

您需要对点表示法模型使用$ parse服务。你的指令中有这样的东西

var getter = $parse(parseattrs.scopeVarToUpdate);
var setter = getter.assign;
getter(scope);   //get value
setter(scope,'value'); //set value

请参阅此处的文档http://docs.angularjs.org/api/ng。$ parse

相关问题