Get value from ngModel in custom directive

2019-07-25 07:15发布

I'm trying to get the value from ngModel from my input through a directive, but I can't get the value.

Here is my code:

angular
    .module('myapp')
    .directive('infoVal', myVal);

function myVal() {
    return {
        link: function(scope, element, attrs, ctrl){
            console.log("Ng Model value");
            console.log(attrs.ngModel.$viewValue);
        }
    }
};

HTML input:

<input type="text"
       class="form-control"
       name="info"
       ng-model="formCtrl.infor"
       info-val>

2条回答
倾城 Initia
2楼-- · 2019-07-25 07:53

You're very close, but you need to make a minor adjustment to your directive in order to be able to pass and access the ng-model item.

angular
    .module('myapp')
    .directive('infoVal', myVal);

function myVal() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            console.log('ng-model value', ngModel.$viewValue);
        }
    }
};
查看更多
你好瞎i
3楼-- · 2019-07-25 08:11

By this sample you can get the first ngModel Value and also onChange Values

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

        app.controller("controller", function ($scope) {

            $scope.test = "hi";

        });


        app.directive("directiveName", function () {
            return {
                restrict: "A",
                replace: true,
                scope: {
                    directiveName: "="
                },
                require: "^ngModel",
                link: function (scope, element, attr, ngModel) {
                    var firstValue = scope.directiveName;

                    console.log("firstValue", firstValue);


                    element.on("input propertychange", function () {
                        console.log("onchange", ngModel.$viewValue);
                    });

                }
            }
        })
<!DOCTYPE html>
<html ng-app="app" ng-controller="controller as ctrl">
<head>
    <title></title>
</head>
<body>

    <input type="text" ng-model="test" directive-name="test" />
    {{test}}

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>

查看更多
登录 后发表回答