在自定义指令中从 ngModel 获取值 [英] Get value from ngModel in custom directive

查看:26
本文介绍了在自定义指令中从 ngModel 获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过指令从我的输入中获取 ngModel 的值,但我无法获取该值.

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

这是我的代码:

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 type="text"
       class="form-control"
       name="info"
       ng-model="formCtrl.infor"
       info-val>

推荐答案

通过此示例,您可以获得第一个 ngModel 值以及 onChange 值

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>

这篇关于在自定义指令中从 ngModel 获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆