AngularJS - 获取从字符串$范围变量 [英] AngularJS - Get $scope variable from string

查看:147
本文介绍了AngularJS - 获取从字符串$范围变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以说我有像这样定义的 $范围变量:

  $ scope.data = {
    过滤:{
        状态:'WA',
        国家:美国
    }
};

我如何访问,在一个单独的服务由字符串?例如 data.filter $范围的情况下

所以说我有像这样一个服务方法:

 函数DoSomething的($范围,VARIABLENAME){
    //我要访问$范围[VARIABLENAME]在这里?
}

我称之为从控制器像这样:

  service.doSomething($范围,'data.filter');


解决方案

您将要使用的 $ EVAL

 函数DoSomething的($范围,变量){
  VAR数据= $ $范围的eval(变量)。  //这个日志{状态:WA,国家美国}
  的console.log(数据);
}

不过,如果你想每次内容的变化做一些功能,这将是preferable使用的 $看

 函数DoSomething的($范围,变量){
  $范围。$腕表(变量,函数(数据){
    //这个日志{状态:WA,国家美国}
    的console.log(数据);
  });
}

So say I have a $scope variable defined like so:

$scope.data = {
    filter: {
        state: 'WA',
        country: 'US'
    }
};

How do I access that in a separate service by string? e.g. data.filter in the context of the $scope.

So say I have a service method like so:

function doSomething($scope, variableName) {
    // I want to access $scope[variableName] here??
}

I would call it from the controller like so:

service.doSomething($scope, 'data.filter');

解决方案

You will want use $eval:

function doSomething($scope, variable) {
  var data = $scope.$eval(variable);

  // this logs {state: "WA", country: "US"}
  console.log(data);
}

However, if you wanted to do some functionality every time the contents changes, it would be preferable to use $watch

function doSomething($scope, variable) {
  $scope.$watch(variable, function(data) {
    // this logs {state: "WA", country: "US"}
    console.log(data);
  });
}

这篇关于AngularJS - 获取从字符串$范围变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆