AngularJS指令中的双向数据绑定

Tia*_*dão 29 javascript data-binding frameworks angularjs

我一直在尝试定义指令,因此我可以在表单中显示不同的"小部件",具体取决于存储在数据库中的字段类型及其参数.我需要对不同类型的场景做出反应,因此需要指令来处理布局.

在玩几个例子时,我想出了一个*有点*的代码:

HTML

<input type="text" ng-model="myModel" style="width: 90%"/>  
<div class="zippy" zippy-title="myModel"></div>
Run Code Online (Sandbox Code Playgroud)

指示

myApp.directive('zippy', function(){
    return {
      restrict: 'C',
      // This HTML will replace the zippy directive.
      transclude: true,
      scope: { title:'=zippyTitle' },
      template: '<input type="text" value="{{title}}"style="width: 90%"/>',
      // The linking function will add behavior to the template
      link: function(scope, element, attrs) {
            // Title element
            element.bind('blur keyup change', function() {
                scope.$apply(read);
            });

            var input = element.children();


            function read() {
                scope.title = input.val();
            }
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

这似乎有效(虽然明显慢于*适当的*angularJS变量绑定)但我认为必须有更好的方法来做到这一点.谁能解释一下这个问题呢?

F L*_*has 27

我不知道为什么你$apply手动触发该方法,因为你实际上并不需要它.

我编辑了您从Angular页面使用的示例并包含了输入.它对我有用:http://jsfiddle.net/6HcGS/2/

HTML

<div ng-app="zippyModule">
  <div ng-controller="Ctrl3">
    Title: <input ng-model="title">
    <hr>
    <div class="zippy" zippy-title="title"></div>
  </div>
</div>?
Run Code Online (Sandbox Code Playgroud)

JS

function Ctrl3($scope) {
  $scope.title = 'Lorem Ipsum';
}

angular.module('zippyModule', [])
  .directive('zippy', function(){
    return {
      restrict: 'C',
      replace: true,
      transclude: true,
      scope: { title:'=zippyTitle' },
      template: '<input type="text" value="{{title}}"style="width: 90%"/>',
      link: function(scope, element, attrs) {
        // Your controller
      }
    }
  });
Run Code Online (Sandbox Code Playgroud)

UPDATE maxisam是对的,您必须使用ng-model而不是将变量绑定到值,如下所示:

<input type="text" ng-model="title" style="width: 90%"/>
Run Code Online (Sandbox Code Playgroud)

这是工作版本:http://jsfiddle.net/6HcGS/3/


max*_*sam 11

你的意思是像这样?

我基本上使用@Flek的例子.
唯一的区别是ng-model='title'

进行双向绑定的技巧是ng-model,它在文档中说明:

ngModel是指示Angular执行双向数据绑定的指令. 它与input,select,textarea一起使用.您也可以轻松编写自己的指令以使用ngModel.

<input type="text" ng-model="title" style="width: 90%"/>
Run Code Online (Sandbox Code Playgroud)