Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS:转移指令和模型访问_Javascript_Angularjs_Transclusion - Fatal编程技术网

Javascript AngularJS:转移指令和模型访问

Javascript AngularJS:转移指令和模型访问,javascript,angularjs,transclusion,Javascript,Angularjs,Transclusion,我正在创建一个智能输入指令,它将包装一个文本输入元素,它需要访问输入元素上的模型,以便操作指令上的一些类 因为输入元素可以是多种类型(文本、电子邮件、密码)中的一种,所以我需要排除指令,并能够为每种类型添加不同类型的验证 我面临的问题(与互联网上的许多其他人一样)是范围继承 以下是我当前的代码 HTML <smart-input ng-model="username"> <span ng-show="isTyping">{{ placeholder }}</sp

我正在创建一个
智能输入
指令,它将包装一个文本输入元素,它需要访问输入元素上的模型,以便操作指令上的一些类

因为输入元素可以是多种类型(文本、电子邮件、密码)中的一种,所以我需要排除指令,并能够为每种类型添加不同类型的验证

我面临的问题(与互联网上的许多其他人一样)是范围继承

以下是我当前的代码 HTML

<smart-input ng-model="username">
  <span ng-show="isTyping">{{ placeholder }}</span>
  <input type="text" name="username" ng-model="username" ng-minlength="4" ng-maxlength="20" required />
</smart-input>

{{占位符}}
JS

angular.module('myApp').directive('smartInput', function ($compile) {
  return {
    restrict: 'E',
    transclude: true,
    replace: true,
    scope: {
      model: '=ngModel'
    },
    template: '<div class="text-input" ng-class="{typing: isTyping}" ng-transclude>' +
              '</div>',
    link: function(scope, element, attrs) {
      scope.isTyping = false;

      scope.$watch('model', function(value) {
        console.log(value);
        scope.isTyping = value.length > 0;
      });
    }
  };
});
angular.module('myApp')。指令('smartInput',函数($compile){
返回{
限制:'E',
是的,
替换:正确,
范围:{
模型:'=ngModel'
},
模板:“”+
'',
链接:函数(范围、元素、属性){
scope.isTyping=false;
范围:$watch('型号'),功能(值){
console.log(值);
scope.isTyping=value.length>0;
});
}
};
});
基本上,$watch函数中的
是未定义的,因此显然我没有正确地执行此操作


因此,我如何将模型绑定到输入字段,同时让指令引用同一对象并能够查看它的值?

当您使用带转换的隔离作用域时,您的作用域没有父/子关系。看起来是这样的:

<controllerScope>
     <smartInputScope>
     <transcludedContentScope>
在html中,我不再需要
$$previsibling

<input type="text" name="username" ng-model="model" ng-minlength="4" ng-maxlength="20" required />


你能用你的代码创建一个JSFIDLE或plunkr吗?它可以解释问题的文本,我想你需要这样的东西:
ng model=“$$prevSibling.model”
但是没有
$$prevSibling
,对吗?@KhanhTO完全正确。我不想把$$previsibling.model放进去,而是让它自动运行。这是因为其他开发人员将使用此指令,我希望使其尽可能简单易用。
<input type="text" name="username" ng-model="model" ng-minlength="4" ng-maxlength="20" required />