Angularjs如何在控制器中获取input [text]的值

时间:2018-03-20 21:13:06

标签: angularjs angularjs-directive angularjs-scope

当数据被更改为源代码时,我希望在控制器中获得input [text]的值:

(function () {
    'use strict';
    var app = angular.module('app', ['ngMaterial']);
    app.controller('ScanDataCtrl', function ($scope) {
        $scope.getScannedData = function () {
            console.log($scope.formScanData.scanDataIReceipt);
        };
    });
    app.directive('scanDataBScan', function ($mdDialog, $sce, $http) {
        return {
            restrict: 'C',
            link: function (scope, element, attrs) {
                element.on('click', function () {
                    scope.getScannedData();
                    // => the value always undefined
                });
            }
        };
    }); 
});

<div ng-controller="ScanDataCtrl">
    <form accept-charset="UTF-8" class="form-inline formScanData" name="formScanData">
        <input ng-model="formScanData.scanDataIReceipt" type="text" required>
       <md-input-container>
            <md-button ng-model="scanDataBScan" class="md-raised md-primary scanDataBScan">Scan</md-button>
        </md-input-container>
    </form>
</div>

此源代码的结果始终是未定义的

请帮帮我。 如果我的英语错误或不好,我很抱歉。

谢谢!

2 个答案:

答案 0 :(得分:0)

使用ng-change指令:

 <input ng-model="formScanData.scanDataIReceipt" type="text" 
        ng-change="getScannedData()" required>

有关详细信息,请参阅AngularJS ng-change Directive API Reference

答案 1 :(得分:0)

(function () {
    'use strict';
    var app = angular.module('app', ['ngMaterial']);
    app.controller('ScanDataCtrl', function ($scope) {
        $scope.getScannedData = function (data) {
            console.log(data);
        };
    });
    app.directive('scanDataBScan', function ($mdDialog, $sce, $http) {
        return {
            restrict: 'C',
            link: function (scope, element, attrs) {
                element.on('click', function () {
                    scope.getScannedData();
                    // => the value always undefined
                });
            }
        };
    }); 
});

<div ng-controller="ScanDataCtrl">
    <form accept-charset="UTF-8" class="form-inline formScanData" name="formScanData">
        <input ng-model="formScanData.scanDataIReceipt" type="text" required>
       <md-input-container>
            <md-button ng-model="scanDataBScan" ng-click="getScannedData(formScanData.scanDataIReceipt)" class="md-raised md-primary scanDataBScan">Scan</md-button>
        </md-input-container>
    </form>
</div>