Get value from ngModel in custom directive

后端 未结 2 1869
执笔经年
执笔经年 2021-01-24 09:46

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\')
         


        
相关标签:
2条回答
  • 2021-01-24 10:15

    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>

    0 讨论(0)
  • 2021-01-24 10:25

    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);
            }
        }
    };
    
    0 讨论(0)
提交回复
热议问题