2016-06-27 3 views
1

지시문을 통해 입력에서 ngModel 값을 가져 오려고하지만이 값을 가져올 수 없습니다.사용자 지정 지시문의 ngModel에서 값 가져 오기

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> 
+0

이 네 번째 매개 변수 될 것이다 지시에 ngModel을 필요로한다 onChange가 값 이 예를 확인하십시오. http://codepen.io/samny/pen/WvygpR/ – abdoutelb

답변

1

당신은 매우 가까운,하지만 당신은 통과 할 수 있도록하기 위해 당신의 지시에 약간의 조정을 할 필요가 여기에

내 코드입니다 항목 ng-model에 액세스하십시오. 이 샘플에 의해

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

function myVal() { 
    return { 
     require: 'ngModel', 
     link: function(scope, element, attrs, ngModel) { 
      console.log('ng-model value', ngModel.$viewValue); 
     } 
    } 
}; 
1

첫 번째 ngModel 값을 얻을 수 있으며,

 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>

관련 문제