簡體   English   中英

Polymer-AngularJS雙向數據綁定

[英]Polymer-AngularJS two-way data binding

我有一些用Polymer創建的自定義元素。 我們稱之為x-input,它看起來像這樣:

<polymer-element name="x-input" attributes="name">
    <template>
        <input type="text" value={{name}}> <span>{{name}}</span>
        <br />
        <input type="range" value={{age}} > <span>{{age}}</span>
    </template>
 </polymer-element>

我有這個HTML我使用Angular:

<html ng-app="testApp">
    <body ng-controller="AppCtrl">
        <input id="outer_input" type="text" ng-model="kids[0].name" value={{kids[0].name}} /> <br />
        <span>name: {{kids[0].name}} age: {{kids[0].age}}</span><br />
        <x-input ng-repeat="kid in kids" name={{kid.name}} age={{kid.age}}>
        </x-input>
    </body>
</html>

這是JS:

var testApp = angular.module('testApp', []);

testApp.controller('AppCtrl', function ($scope, $http)
{
    $scope.kids = [{"name": "Din", "age": 11}, {"name": "Dina", "age": 17}];
}

問題在於雙向數據綁定。 當我更改#outer_input輸入值時,x輸入內部值(名稱和年齡)會發生變化。

但是當我更改自定義元素輸入時,只更改了內部綁定變量。

如何在聚合物元素中更改綁定變量的值,它將更改模型和所有外部綁定的UI和數據(雙向綁定)?

謝謝

如果您告訴它,Polymer會將模型更改反映回已發布的屬性(其屬性),但問題是Angular不會觀察到屬性的綁定。

有一個補丁可以讓你的工作像你想要的那樣: https//github.com/eee-c/angular-bind-polymer

更多信息: http//blog.sethladd.com/2014/02/angular-and-polymer-data-binding.html

我啟動了ng-polymer-elements項目,它允許您以類似Angular的方式在Web組件和Angular之間進行雙向綁定:

<input ng-model="model"/>
<paper-input ng-model="model"></paper-elements>

它支持聚合物核心和紙張元素,可以配置任何Web組件。

我相信這就是你正在尋找簡單透明的雙向數據綁定和擴展到更多自定義元素和javascript不能飛鏢的能力

NG聚合物元素

這是我的工作解決方案, ng-polymer-elements對我不起作用($ dirty,$ pristine等不工作)。 這是非常直接的IMO

angular.module 'tinizen.admin.ui'
.directive 'paperInput', ->
  restrict: 'E'
  require: 'ngModel'
  link: (scope, elem, attrs, ctrl)->

    watcher = ->
      if ctrl.$dirty then ctrl.$invalid else false

    scope.$watch watcher, (invalid)->
      elem[0].invalid = invalid

    updateModel = (inputValue)-> ctrl.$setViewValue inputValue

    ## attrs.$observe 'inputValue', updateModel not working
    ## so I have to use on 'input'
    elem.on 'input', ->
      scope.$apply ->
        updateModel elem.prop('inputValue')

    updateModel()

    ctrl.$render = ->
      elem.prop 'inputValue', ctrl.$viewValue

根據他們的文檔,當綁定到本機元素時,您必須添加額外的綁定表示法

https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#two-way-native

此處{{name}}將更新輸入事件,{{age}}僅更改事件

<polymer-element name="x-input" attributes="name">
    <template>
        <input type="text" value={{name::input}}> <span>{{name}}</span>
        <br />
        <input type="range" value={{age::change}} > <span>{{age}}</span>
    </template>
 </polymer-element>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM