2016-06-27 8 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>

関連する問題