无法使用双向绑定更改指令范围内的父范围变量

时间:2016-10-17 13:35:21

标签: angularjs angularjs-directive

我正在尝试创建一个以用户名作为输入的自定义指令。然后验证并检查用户名是否可用。如果用户名不可用,我想将一些值传递回父控制器。

<!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>

总之,我试图根据某些条件从指令范围更改parentVariable的值,但它没有发生,请让我知道我做错了什么。

1 个答案:

答案 0 :(得分:0)

您指定了隔离范围参数set /A "_DIGITS=12",但在模板中没有传递给它的值:

parentVariable

你需要:

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

这是一个孤立的例子。

&#13;
&#13;
<input type="text" is-unique="{url: 'http://WWW.GOOGLE.COM'}" parent-variable="parentVariable" ng-model="role"/>
&#13;
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);
    }
  }
});
&#13;
&#13;
&#13;