$ scope.watch在两个不同的角度页面之间不起作用

时间:2016-11-10 11:39:14

标签: angularjs angularjs-scope angularjs-watch

以下代码在一个页面中使用不同的控制器,但是当我将值从一个页面传递到另一个页面时,scope.watch不起作用。你怎么能这样做?下面是我的代码。

 .factory('Data', function () {

    var data = {
        LastName: '',
    }
    return {
        getLastName: function () {
            return data.LastName;
        },
        setLastName: function (lastname) {
            data.LastName = lastname;
        }
    }
}
    //FIRST CONTROLLER
    $scope.lastname = '';
    $scope.$watch('lastname', function (newValue2, oldValue2) {
        if (newValue2 !== oldValue2)
            Data.setLastName(newValue2);
    });
    //GET FIRST CONTROLLER INTO SECOND
    $scope.$watch(function () {
        return Data.getLastName();
    }, function (newValue2, oldValue2) {
        if (newValue2 !== oldValue2)
            $scope.lastname = newValue2;
    });
    //form
    //Firstcontroller
    < input type = "text" 
            name="lastname" 
            placeholder = "Suhr" 
            ng-model="lastname"
            ng-minlength="3" required />

1 个答案:

答案 0 :(得分:1)

移植所有代码并且它有效!

&#13;
&#13;
angular.module("test", [])
  .controller('Test1', Test1)
  .controller('Test2', Test2)
  .factory('Data', Data);

function Test1($scope, Data) {
  $scope.lastname = '';

  $scope.$watch('lastname', function(newValue2, oldValue2) {
    if (newValue2 !== oldValue2)
      Data.setLastName(newValue2);
  });
}

function Test2($scope, Data) {
  $scope.$watch(function() {
    return Data.getLastName();
  }, function(newValue2, oldValue2) {
    if (newValue2 !== oldValue2)
      $scope.lastname = newValue2;
  });
}

function Data() {
  var data = {
    LastName: '',
  }

  return {
    getLastName: function() {
      return data.LastName;
    },
    setLastName: function(lastname) {
      data.LastName = lastname;
    }
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

<div ng-app="test">
  <div ng-controller="Test1">
    <input type="text" name="lastname" ng-model="lastname" placeholder="Suhr" ng-minlength="3" required>
  </div>

  <div ng-controller="Test2">
    {{lastname}}
  </div>
</div>
&#13;
&#13;
&#13;