当选中复选框时,Angular - Input1 Value Input2相同的值

时间:2014-03-05 03:55:47

标签: angularjs angularjs-directive

我有问题,这是我的代码

<div ng-app="pesan">
    <div ng-controller="datapesan">
        <input type="text" ng-model="nama" name="nama1" />
        <br />
        <input type="text" ng-model="telephone" name="telephone1" />
        <hr />
        <input type="checkbox" name="nama_same" ng-model="check" ng-true-value="Yes" ng-false-value="Tidak" />Same Buyer ({{check}})
        <br />
        <input type="text" ng-model="nama1"/>
        <br />
        <input type="text" ng-model="telephone1"/>
    </div>
</div>

我的控制器

var pesan = angular.module("pesan", []);

pesan.controller("datapesan", function($scope){
    if($scope.check){
        $scope.nama1=$scope.nama;
        $scope.telephone1=$scope.telephone;
    }
});

我希望<input name="nama1"><input name="nama">具有相同的值,而<input name="telephone1"><input name="telephone">具有相同的值,并且已选中条件复选框!如果未选中复选框,则每个输入可以具有不同的值

3 个答案:

答案 0 :(得分:3)

试试这个;

    var pesan = angular.module("pesan", []);

        pesan.controller("datapesan", function($scope){

          $scope.$watch('check',function(){

            if($scope.check === 'Yes'){
               $scope.nama1=$scope.nama;
                $scope.telephone1=$scope.telephone;
            } else {
                $scope.nama1='';
                $scope.telephone1='';
            }
          });


    });

答案 1 :(得分:2)

你应该使用$ scope。$ watch来查看$scope.check变量。用户单击该复选框后,将调用watchCheck。由于您已将ng-true-value定义为“是”,因此您必须在checked ==== 'Yes'更改时检查$scope.check

$scope.$watch('check', function watchCheck(checked) {
    if (checked === 'Yes') {
        $scope.nama1=$scope.nama;
        $scope.telephone1=$scope.telephone;
    }
});

答案 2 :(得分:2)

以下是plunker http://plnkr.co/edit/G4H4YfwTKO1jmiFDFIu6?p=preview       var pesan = angular.module(“pesan”,[]);

    pesan.controller("datapesan", function($scope){

      $scope.$watch('check',function(){

        if($scope.check){
           $scope.nama1=$scope.nama;
            $scope.telephone1=$scope.telephone;
        }
      });


});