0

下面的代码在具有不同控制器的一页内工作,但是当我将值从一页传递到另一页时,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 />
4

1 回答 1

1

移植所有代码,它就可以工作了!

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;
    }
  }
}
<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>

于 2016-11-10T12:01:14.710 回答