2013-12-10 159 views
0

我试图创建一个自定义电子邮件文本框组件,它有两个字段。要做到这一点,我有这个模板:AngularJS:指令绑定

<div class="custom"> 
    <div class="username" contenteditable="true"></div> 
    <div class="domain">@{{ domainValue }}</div> 
</div> 

所以我可以调用指令调用该模板,如:

<div ng-custom-txt></div> 

从我希望能够通过不同类型的值的指令(从模型域)被称为“NG-domaindata”,如:

<div ng-domaindata="mydomain1.com" ng-custom-txt></div> 

我的问题是,我该怎么绑定“域”字段是在模板中的指令?

我试图用这种方法,但没有成功可言:

模板:customtemplate.html

<div class="custom"> 
    <div class="username" contenteditable="true"></div> 
    <div class="domain">@{{ domainValue }}</div> 
</div> 

<div ng-domaindata="mydomain1.com" ng-custom-txt></div> 
<div ng-domaindata="mydomain2.com" ng-custom-txt></div> 

指令

app.directive('ngCustomTxt', function() { 
    return { 
    restrict: 'A', 
    require: '^ngModel', 
    templateUrl: 'customtemplate.html', 
    link: function(scope, element, attrs, ctrl) { 
     scope.$watch(attrs.ngDomaindata, function (newValue){ 
     scope.domainValue = newValue; 
    } 
    } 
    } 
}); 

显然它不起作用,因为我无法区分这两个元素,有人可以帮我解决这个问题吗?

+0

只是一个快速提示。避免使用带ng前缀的自己的指令。 –

回答

0

为此指令创建作用域。看来该指令正在获得共享范围。 声明一个作用域将强制获得一个新的作用域实例。

另外,观察者在创建实例时执行。在你的情况下,它的设置未定义为scope.domainData值。

尝试检查newValue是否有效,或使用$ observe功能。

app.directive('customTxt', function($parse) { 
    return { 
    restrict: 'A', 
    templateUrl: 'customtemplate.html', 
    scope : {}, 
    link: function(scope, element, attrs, ctrl) { 
     scope.domainValue = attrs.domaindata; 
     scope.$watch(attrs.domaindata, function (newValue){ 
      console.log('This code will execute when the instance where created. Getting a undefined newValue variable: ', newValue); 
      // verifying if the value is valid to set to the scope. 
      if (newValue != null) { 
       scope.domainValue = newValue; 
      } 
     }); 
    } 
    }; 
}); 

Working plunker

+0

非常感谢!它越来越近了,但我试图去到下一个层次,我觉得这种方法不行。 我自己解释一下: 模型的值是动态的,由另一个控制器更新并保存在一般范围内,所以我需要以某种方式将一般范围内的值绑定到本地。 有了这个解决方案,我无法访问一般范围,那怎么能呢? – DreaMTT

+0

嗯好的,看看这个运动员,看看是否有帮助:http://plnkr.co/edit/eAFdwi4jztR197wo0QdO?p=info –

+0

非常感谢Deividi!现在它变得更接近了!我需要的是一些短小的范围之间的双向绑定,我只是编辑你的掠夺者,告诉你我需要什么,请看看:http://plnkr.co/edit/IBpyZbCV7pOB25oZSYD7?p=preview 所以,它似乎有效,但是当我想从全局范围更新一个域时,单击“更改值”,它不会更新本地范围。对? – DreaMTT