JavaScript对象的动态属性变为null

时间:2016-09-06 21:01:56

标签: javascript angularjs

我尝试使用ng-model在javascript对象上设置动态属性。但是我无法创建它,因为我总是为该属性获取null。我有不同的方法将值从变量self.username复制到self.params javascript对象中。

请参阅此plnkr

的index.html

<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <link rel="stylesheet" href="style.css">
  <script src="//code.angularjs.org/1.2.26/angular.js"></script>
  <script src="https://code.angularjs.org/1.2.26/angular-route.min.js">
  </script>
  <script src="app.js"></script>
  <script src="routes.js"></script>
</head>

<body>
  <a href="#/carriers">Carriers</a>

  <div class="mainContainer" ng-view></div>
</body>

</html>

routes.js

myApp.config(function($routeProvider) {
  $routeProvider
    .when('/carriers', {
      templateUrl: 'carriers.html',
      controller: 'MainCtrl',
      controllerAs: 'mainCtrl'
    })
    .otherwise({
      redirectTo: '/'
    });
});

Carriers.html

<input type="text"  placeholder="username" ng-model="mainCtrl.username" />
<button  ng-click="mainCtrl.login()">Login</button>

app.js

var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('MainCtrl', function() {
  var self = this;
  self.username = '';
  self.login = login;
  self.params = {
    username: self.username //doesnt work
  };
  //self.params.username=angular.copy(self.username);    //doesnt work
  //self.params['username']=self.username; //doesnt work
  function login() {
    //   alert(self.username);
    console.dir(self.username); // works
    console.dir(self.params); // username:'' getting empty string for username property
  }
});

1 个答案:

答案 0 :(得分:1)

由于您创建了一个新对象并将self.params.username的值设置为self.params的值,因此该值不会更新。 self.params.username未引用self.params它是根据创建对象时的值设置的。{/ p>

如果要将self.params.username绑定到输入,则可以将输入模型更改为:

<input type="text"  placeholder="username" ng-model="mainCtrl.params.username" />

另一种方法是观看self.username并使用$watch

self.params.username的值设置为新值
// watch mainCtrl.username for any changes
$scope.$watch('mainCtrl.username', function(newValue, oldValue) {

    // set self.params.username from the new value
    self.params.username = newValue;

});