一个控制器中的变量受另一个控制器中相同名称变量的影响

时间:2015-07-28 15:14:28

标签: angularjs

我在使用angularjs和rails的项目中。所以,我也使用这个库:

https://github.com/FineLinePrototyping/angularjs-rails-resource

好吧,当我使用控制器作为angularjs的语法时,会发生一些奇怪的行为。你可以在这个plunker示例中看到:

http://plnkr.co/edit/i4Ohhh8llS7WN68sLX5q?p=preview

第一个控制器中的远程调用以某种方式使用angularjs-rails-resource库返回的promise对象是设置属于第二个控制器的实例变量。我不知道它是否是库中的错误,或者我应该知道的角度行为。无论如何,这显然是一种不良行为。

以下是相同的plunker代码(index.html):

<!doctype html>
<html ng-app="Demo">
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.js"></script>
    <script src="https://rawgit.com/FineLinePrototyping/dist-angularjs-rails-resource/master/angularjs-rails-resource.min.js"></script>
    <script src="example.js"></script>
  </head>
  <body>

    <div ng-controller="Controller1 as ctrl1">
      <form>
        <label>should appear first remote</label>
        <input type="text" ng-model="ctrl1.remote.name"/><br>
        <label>should appear first local</label>
        <input type="text" ng-model="ctrl1.local.name"/>
      </form>
    </div>

    <br>

    <div ng-controller="Controller2 as ctrl2">
      <form>
        <label>should appear second local</label>
        <input type="text" ng-model="ctrl2.remote.name"/><br>
        <label>should appear second local</label>
        <input type="text" ng-model="ctrl2.local.name"/>
      </form>
    </div>


  </body>
</html>

我的angularjs代码(example.js):

angular.module('Demo', ['rails']);
angular.module('Demo').controller('Controller1', ['$scope', 'Remote', function($scope, Remote) {

  ctrl = this;

  ctrl.remote = {};
  Remote.get().then(function(remote) {
      ctrl.remote = remote;
  });

  ctrl.local = {};
  ctrl.local.name = "first local";

}]);
angular.module('Demo').controller('Controller2', ['$scope', function($scope) {

  ctrl = this;

  // SAME VARIABLE NAME
  // WILL RECEIVE VALUE FROM REMOTE CALL ON FIRST CONTROLLER!!!
  ctrl.remote = {};
  ctrl.remote.name = "second local";

  // SAME VARIABLE NAME
  ctrl.local = {};
  ctrl.local.name = "second local";

}])
angular.module('Demo').factory('Remote', [
    'railsResourceFactory',
    'railsSerializer',
    function (railsResourceFactory, railsSerializer) {
        return railsResourceFactory({
            url:'clients.json',
            name: 'remote',
        })
    }]
);

clients.json

{
    "name":"first remote"
}

任何ideias如何解决这个问题而不必更改变量名以避免冲突?因为这样我们就会掩盖这个问题。

我将问题报告给angularjs-rails-resource库,但直到现在才回答。

1 个答案:

答案 0 :(得分:3)

在声明变量时需要使用var,否则它们会全局变化。

使用 var ctrl = this;而非ctrl = this;

此外,&#39;使用严格的&#39;是一件好事(它在这些情况下有帮助)