如何将数据从输入传递到自定义服务?

时间:2017-05-16 13:10:05

标签: javascript angularjs angularjs-service

我是AngularJS的新手,我遇到了一个问题:如何显示插入输入框的数字的十六进制等值?

我正在使用ng-change查看输入是否已修改,输出也应根据输入进行更改。

这是代码:

<div ng-app="myApp" ng-controller="myCtrl">
  <input type="number" ng-model="in" ng-change="hex(in)"> 
  {{in}} <br>{{hex}}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<script>
  var app = angular.module('myApp', []);

  app.service('hexafy', function() {
    this.myFunc = function (x) {
      return x.toString(16);
    }
  });
    
  app.controller('myCtrl', function($scope, hexafy) {
    $scope.in= 11;
    $scope.hex = hexafy.myFunc($scope.in);
  });
</script>

2 个答案:

答案 0 :(得分:1)

为什么它不起作用?

在您的输入中,您尝试调用函数:

$scope.hex

但是$scope.hex = hexafy.myFunc($scope.in); 不是你控制器中的一个功能:

$scope.hex = function() {
    $scope.result = hexafy.myFunc($scope.in);
}

如何解决?

将其更改为:

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

app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});

app.controller('myCtrl', function($scope, hexafy) {
    $scope.in= 11;
    $scope.hex = function() {
        $scope.result = hexafy.myFunc($scope.in);
    };
});

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
    <input type="number" ng-model="in" ng-change="hex()"> 
    {{in}} <br>{{result}}
</div>
&#13;
$.post("{{ route('knitting.table', ['requestingDepartment' => 'Warping' , 'workdone' => 0]) }}", { _token: token } ,function(){})
.done(function(data1) {
    $('#table1').bootstrapTable('load', data1);
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

创建Plunker。问题是你使用函数名作为赋值。

 <input type="number" ng-model="in" ng-change="convertToHex(in)"> 
 $scope.convertToHex= function(value) {
       $scope.hex = hexafy.myFunc(value);
    }