指令拾取第二个值

时间:2016-04-08 06:19:54

标签: angularjs

我有这样的指令

app.directive('isUnique', ['$http', function($http) {
    return {
      require: 'ngModel',
      scope: {
          ignore: '<',
          ngModel: '='
      },
      link: function(scope, ele, attrs, c) {
        attrs.$observe('isUnique', function(postToUrl) {
          console.log('Ignore value: ' + scope.ignore);
          console.log('Model has value: ' + scope.ngModel);
          console.log('Url to Post ' + postToUrl);
        });
      }
    }
}]);

并像这样使用

<input type="text" ng-model="name" ignore="::name" is-unique="/to/some/url?name={{name}}" />  

问题是加载应用程序时scope.ignoreundefined,但是我在文本框scope.ignore中首先输入的内容设置为该值。我想如果scope.ignore在开始时有未定义的值,则必须保持undefined。有没有办法解决它?

这里是plunkr:https://plnkr.co/edit/kAsTYiPx2AsotVbBTnNf?p=preview

1 个答案:

答案 0 :(得分:0)

嗯,这是使用::时一次性绑定的功能,Angular会观察,直到变量获得undefined以外的任何值。但是如果你想要这种行为,那么使用这样的局部变量:

app.directive('isUnique', ['$http', function($http) {
    return {
      require: 'ngModel',
      scope: {
          ignore: '=',
          ngModel: '='
      },
      link: function(scope, ele, attrs, c) {
        var localIgnore = scope.ignore;

        attrs.$observe('isUnique', function(postToUrl) {
          console.log('Ignore value: ' + localIgnore);
          console.log('Model has value: ' + scope.ngModel);
          console.log('Url to Post ' + postToUrl);
        });
      }
    }
}]);

第二个选项可以是修改你的代码:

<input type="text" ng-model="name" ignore="{{::name}}" is-unique="/to/some/url?name={{name}}" />

然后从指令的范围中移除ignore: '=',

app.directive('isUnique', ['$http', function($http) {
    return {
      require: 'ngModel',
      scope: {
          ngModel: '='
      },
      link: function(scope, ele, attrs, c) {
        attrs.$observe('isUnique', function(postToUrl) {
          console.log('Ignore value: ' + attrs.ignore);
          console.log('Model has value: ' + scope.ngModel);
          console.log('Url to Post ' + postToUrl);
        });
      }
    }
}]);