Создание динамического сервиса AngularJS с вводом - PullRequest
0 голосов
/ 30 апреля 2018

Я новичок в разработке AngularJS. Я пытаюсь построить динамический сервис, который обновляет вывод с элементами ввода. Но я получаю ошибку каждый раз.

Что я делаю не так при объявлении сервисных функций. Вот мой HTML-код

<div ng-app="myApp" ng-controller="myCtrl">
    <p>A custom service with a method that converts a given number into a hexadecimal number.</p>
    <label>input a number</label>
    <input ng-init="m5=0" ng-model="m5"></input>
    <p>The hexadecimal value of {{m5}} is:</p>
    <h1>{{hex}}</h1>
</div>

мое приложение angularJS выглядит следующим образом:

var app = angular.module('myApp', []);
    app.service('hexafy', function() {
        this.myFunc = function (x) {
            return x.toString(16);
        }
    });
    app.controller('myCtrl', function($scope, hexafy) {
        $scope.hex = hexafy.myFunc(parseInt($scope.m5));
    });

Но мой вывод {{hex}} не является динамическим. Показывает статическое значение NaN.

Заранее спасибо

Ответы [ 2 ]

0 голосов
/ 30 апреля 2018

Одним из подходов является использование директивы ng-change :

<div ng-app="myApp" ng-controller="myCtrl">
    <p>A custom service with a method that converts a given number into a hexadecimal number.</p>
    <label>input a number</label>
    <input ng-init="m5=0" ng-model="m5"
           ng-change="hex=toHex(m5)" />  ̶<̶/̶i̶n̶p̶u̶t̶>̶
    <p>The hexadecimal value of {{m5}} is:</p>
    <h1>{{hex}}</h1>
</div>

JS

app.service('hexafy', function() {
    this.myFunc = function (x) {
        return parseInt(x).toString(16);
    }
});
app.controller('myCtrl', function($scope, hexafy) {
    $scope.toHex = hexafy.myFunc;
});

При каждом изменении входного значения будет обновляться $scope.hex.

Для получения дополнительной информации см. Справочник по API AngularJS ng-change .

0 голосов
/ 30 апреля 2018

Попробуйте ввести указанный ниже сервисный код:

app.service('hexafy', function() {
    this.myFunc = function (x) {
        return Number(x).toString(16);
    }
});
app.controller('myCtrl', function($scope, hexafy) {
    $scope.hex = hexafy.myFunc($scope.m5);
});

Надеюсь, это подойдет вам.

Но я предпочитаю использовать параметр фильтра для этого. Вы можете попробовать фильтр как:
AngulrJS

var app = angular.module('myApp', []);

//Filter to conver input number into hexadecimal number 
app.filter('hexafy', function () {
  return function(x) {
    return Number(x).toString(16);
  };
});
app.controller('myCtrl', ['$scope', 'hexafyFilter', function($scope, hexafyFilter) {
    $scope.m5 = 0;
}]);

HTML

<div ng-app="myApp" ng-controller="myCtrl">
    <p>A custom service with a method that converts a given number into a hexadecimal number.</p>
    <label>input a number</label>
    <input type="number" ng-model="m5"></input>
    <p>The hexadecimal value of {{m5}} is:</p>
    <h1>{{ m5 | hexafy }}</h1>
</div>

Наслаждайтесь решением. :)

...