如何使用一个控制器为多个输入使用相同的逻辑?

时间:2016-07-12 18:19:00

标签: angularjs forms angularjs-ng-model

我有以下场景,一个包含多个输入的表单,我需要以相同的方式计算每个输入,但将值返回到不同的字段

<div class="row">
        <input type="number" min="1" class="form-control" id="InputValorFOR" placeholder="" ng-change="findModifier()" ng-model="atrb.for">
        <p>{{mod.for}}</p>
</div>
<div class="row">
        <input type="number" min="1" class="form-control" id="InputValorDES" placeholder="" ng-change="findModifier()" ng-model="atrb.des">
        <p>{{mod.des}}</p>
</div>

控制器:

app.controller('atributosCtrl', function($scope){

findModifier = function() {        
    if ($scope.atrb > 1 && $scope.atrb <10)
    {
        if ($scope.atrb % 2 == 0)
        {
            $scope.mod = (($scope.atrb / 2) - 5);
        }        
    }
};    
$scope.$watch('atrb', findModifier); });

我想更改mod.for或mod.des的值,而不必为每个输入编写控制器。但我不知道如何从我正在修改的输入中传递模型的名称

2 个答案:

答案 0 :(得分:0)

我认为你期待这样的事情。您可以使用下面的链接函数编写自定义指令

(function () {
    "use strict";
    angular.module("app").directive("notifypropertychanged", notifypropertychanged);
    function notifypropertychanged() {
        var directive = {
            require: "ngModel",
            link: function ($scope, element, attrs, ngModel) {
                $scope.$watch(attrs["notifypropertychanged"], function (newVal, oldVal) {

                    var initialValue = attrs["oldvalue"];

                });
            }
        };
        return directive;
    }
})();

在您的输入

上应用此指令
 <input type="number" min="1" class="form-control" notifypropertychanged="atrb.des"  oldvalue=" {{::atrb.des}} " id="InputValorDES" placeholder="" ng-model="atrb.des"> 

每当价值发生变化时,它都会点击自定义观看

我希望这会有所帮助

答案 1 :(得分:0)

我不知道你到底想要什么,但我对你的代码进行了一些修改以使其正常工作。请在这里评论你想要的内容,我会帮助你。

您的HTML已修改:

  <body ng-controller="atributosCtrl">
    <div class="row">
        <input type="number" min="1" class="form-control" id="InputValorFOR" placeholder="" ng-change="findModifier('for')" ng-model="atrb.for">
        <p>{{mod.for}}</p>
    </div>
    <div class="row">
        <input type="number" min="1" class="form-control" id="InputValorDES" placeholder="" ng-change="findModifier('des')" ng-model="atrb.des">
        <p>{{mod.des}}</p>
    </div>
  </body>

你的JS修改了:

app.controller('atributosCtrl', function($scope){
  $scope.atrb = {
    for: null,
    des: null
  };
  $scope.mod = {
    for: null,
    des: null
  };

  $scope.findModifier = function(type) {
    $scope.mod[type] = null;
    if ($scope.atrb[type] > 1 && $scope.atrb[type] <10)
    {
        if ($scope.atrb[type] % 2 === 0)
        {
            $scope.mod[type] = (($scope.atrb[type] / 2) - 5);
        }        
    }
  }
});

Plunker: https://plnkr.co/edit/aCNJQyfYXZ5vU1rc381S