2016-10-17 5 views
0

入力としてユーザー名を使用するカスタムディレクティブを作成しようとしています。次に、ユーザー名が使用可能かどうかを検証し、チェックします。ユーザー名が利用できない場合は、親コントローラにいくつかの値を戻したいと思います。私はいくつかの条件に応じて、指示範囲からparentVariableの値を変更しようとしていますが、そのは起きていない要約双方向バインディングを使用して、親スコープ変数をディレクティブスコープから変更できません。

<!DOCTYPE html> 
<html> 
<head lang="en"> 
    <meta charset="utf-8"> 
    <title>AngularJS Isolate Scope</title> 

</head> 
<body> 

    <div ng-app="mainApp"> 
    <div ng-controller="AppCtrl"> 

     <div> From Controller : <input type="text" ng-model="ctrlRole"></div><br> 
     {{parentVariable}} 

      <input type="text" is-unique="{url: 'http://WWW.GOOGLE.COM'}" ng-model="role"/> 

    </div> 
</div> 


    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> 
    <script> 

    var app = angular.module('mainApp', []); 
app.controller("AppCtrl", function($scope){ 
    $scope.ctrlRole = "Development"; 
      $scope.parentVariable = "a"; 
}); 

app.directive("isUnique", function() { 

return { 
    restrict : 'A', 
    require : 'ngModel', 
    transclude: 'true', 
     scope:{ 
     parentVariable:"=" 
    }, 
    link : function(scope, element, attrs, ngModel) { 
     element.bind('blur', function (e) { 
       if (!ngModel || !element.val()) return; 

       var keyProperty = scope.$eval(attrs.isUnique); 

       console.log('this is the keyProperty we have received from the front end ' + keyProperty.url); 

       var currentValue = element.val(); 
       console.log('this is the data we are going to validate ' + currentValue); 

       if(currentValue == 'AE'){ 
     console.log('Changing the value '); 
      scope.parentVariable = 'b'; 
     } 

       }); 

     } 
    } 
}); 

    </script> 
</body> 

、私は私が間違っているのか知っている聞かせください。

+0

私は外側のスコープへの結合を示すコードスニペット、と私の答えを更新しました。それが役に立てば幸い! – dinony

答えて

0

あなたは分離株スコープパラメータparentVariableを指定しますが、テンプレートに渡された値がない:

あなたが必要となる

<input type="text" is-unique="{url: 'http://WWW.GOOGLE.COM'}" ng-model="role"/>

ここ

<input type="text" is-unique="{url: 'http://WWW.GOOGLE.COM'}" parent-variable="parentVariable" ng-model="role"/>

、あります孤立した例。

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

 
app.controller('MainCtrl', function($scope) { 
 
    $scope.foo = 'foo'; 
 
}); 
 

 
app.directive('testDir', function($timeout) { 
 
    return { 
 
    restrict: 'A', 
 
    scope: { 
 
     val: '=' 
 
    }, 
 
    link: function(scope) { 
 
     console.log(scope.val);  
 
     
 
     $timeout(function() { 
 
     scope.val = 'bar'; 
 
     }, 1000); 
 
    } 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="test"> 
 
    <div ng-controller="MainCtrl"> 
 
    {{foo}} 
 
    <div test-dir val="foo"></div> 
 
    </div> 
 
</div>

関連する問題