Возникли проблемы с использованием ngChange для обновления модели

Я только начал изучать основы Angular. Я пытаюсь сделать конвертер годовой зарплаты, просто для удовольствия. У меня возникают трудности с ежемесячным обновлением ng-модели, когда годовая модель изменяется пользователем. Поля являются входными тегами. Вот код

    <!doctype html>
<html ng-app="salaryApp">
    <head>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container" ng-controller="converter">
            <h1>Salary converter</h1>
            <div class="form-group">
                <label>Annual Salary</label>
                <input type="number" class="form-control" placeholder="0" ng-model="yearly" ng-change="reCalculate()" >
                <br>
                <label>Monthly Salary</label>
                <input type="number" class="form-control" placeholder="0" ng-model="monthly" disabled>
            </div>

        </div>
        <!--<div ng-controller="converter">
            Write some text in textbox:
            <input type="text">

            <h1>Hello {{ yearly }}</h1>
            <h1>Hello {{ monthly }}</h1>
        </div>-->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
        <!--<script src="salaryConverter.js"></script>-->
        <script type="text/javascript">
            var app = angular.module('salaryApp', []);



app.controller('converter', function($scope) {
  $scope.yearly = 80000;
  console.log("log1");
  $scope.monthly = $scope.yearly / 12;
  console.log("log2");

    function reCalculate() {
        console.log("function was run");
        return $scope.yearly /12.00;

  }

});
</script>

    </body>
</html>

Вот plnkr http://plnkr.co/edit/26y0JRR7iVcrLOBlm7D2?p=preview


person Sammy Kumar    schedule 04.06.2015    source источник


Ответы (4)


Вам нужно использовать его как свойство scope. Здесь :

function reCalculate() {
        console.log("function was run");
        return $scope.yearly /12.00;

  }

должно быть

  $scope.reCalculate = function () {
        console.log("function was run");
        $scope.monthly=$scope.yearly /12.00;//Don't return, you neet to assign

  }
person Zee    schedule 04.06.2015
comment
Спасибо Зи! Так просто! Я много раз читал документацию, но пропустил эту конкретную деталь. - person Sammy Kumar; 04.06.2015
comment
@squid267 НП. Рад помочь :) - person Zee; 04.06.2015

Определите функцию, как в $scope, которая будет вызываться из представления, и присвойте значение monthly вместо возврата.

$scope.reCalculate = function () {
    console.log("function was run");
    $scope.monthly = $scope.yearly / 12.00;
}

ДЕМО

person Satpal    schedule 04.06.2015

Вам нужно добавить метод reCalculate в вашу область видимости:

app.controller('converter', function($scope) {
  $scope.yearly = 80000;
  $scope.reCalculate = reCalculate; <--- THIS LINE
  console.log("log1");
  $scope.monthly = $scope.yearly / 12;
  console.log("log2");

    function reCalculate() {
        console.log("function was run");
        return $scope.yearly /12.00;

  }

});

Вы также можете добавить его напрямую:

$scope.reCalculate = function()...

Но я рекомендую следовать некоторым руководствам по стилю написания контроллеров: https://github.com/johnpapa/angular-styleguide

person stian.net    schedule 04.06.2015

app.controller('converter', function($scope) {
  $scope.yearly = 80000;
  console.log("log1");
  $scope.monthly = $scope.yearly / 12;
  console.log("log2");

    $scope.reCalculate = function () {
        console.log("function was run");
        $scope.monthly = $scope.yearly / 12;

  }

});

Вот как работает ваш плункер

person Jorge Casariego    schedule 04.06.2015