AngularJs引用另一个范围变量

时间:2015-05-12 13:06:58

标签: javascript angularjs

我正在开发一个简单的应用程序以供演示使用,我遇到以下问题:我的控制器中有两个对象(凭据和authServer),我想引用authServer对象中的凭据属性。 scope.credential属性都绑定到输入字段,但在我的authServer对象中不会更新onchange。

我知道我可以通过$ watch实现这一目标,但我正在寻找一种更优雅的方式。

var app = angular.module('clientApp', []);
app.controller('myCtrl', function($scope) {
    $scope.credentials = {
      'username': null,
      'password' : null
    };

    $scope.authServer = {
      'url' : 'http://localhost:9000/auth', 
      'request' : {
        'grant_type': null,
        'scope': null,
        'client_id': null,
        'client_secret': null, 
        'username' : $scope.credentials.username,
        'password' : $scope.credentials.password
      }
    };
});

3 个答案:

答案 0 :(得分:0)

将此部分更改为以下

$scope.authServer = {
  'url' : 'http://localhost:9000/auth', 
  'request' : {
    'grant_type': null,
    'scope': null,
    'client_id': null,
    'client_secret': null, 
    'username' : $scope.credentials.username,
    'password' : $scope.credentials.password
  }
};

您想引用'$ scope.credentials',因为这是一个对象,对象通过引用传递,其中$ scope.credentials.username按值传递。

$scope.authServer = {
  'url' : 'http://localhost:9000/auth', 
  'request' : $scope.credentials
};

$scope.authServer.request['grant_type'] = null;
$scope.authServer.request['scope'] = null;
$scope.authServer.request['client_id'] = null;
$scope.authServer.request['client_secret'] = null;

答案 1 :(得分:0)

解决方案1 ​​

仅在您需要使用时才设置$scope.authServer

$scope.doRequest = function() {
  $scope.authServer = {
  'url' : 'http://localhost:9000/auth', 
  'request' : {
    'grant_type': null,
    'scope': null,
    'client_id': null,
    'client_secret': null, 
    'username' : $scope.credentials.username,
    'password' : $scope.credentials.password
  };
  // use $scope.authServer here
};

解决方案2

在控制器内使用$scope.$watch('credentials', function(){ $scope.authServer=/*...*/ }, true);

解决方案3

(参见杨力的回答),引用对象 $scope.credentials而不是单个属性

答案 2 :(得分:0)

您需要分配凭据 object ,这是一种引用类型。用户名和密码是基元,它们是值类型。

Plunker Example

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
 $scope.credentials = {
      'username': null,
      'password' : null
    };

    $scope.authServer = {
      'url' : 'http://localhost:9000/auth', 
      'request' : {
        'grant_type': null,
        'scope': null,
        'client_id': null,
        'client_secret': null, 
        'credentials': $scope.credentials
      }
    };
});