2013-12-10 154 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