【问题标题】:Two way data binding in AngularJS DirectivesAngularJS 指令中的两种数据绑定方式
【发布时间】:2012-10-28 23:19:54
【问题描述】:

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

在玩几个例子的同时,我想出了一个 *kinda* 工作的代码:

HTML

<input type="text" ng-model="myModel" style="width: 90%"/>  
<div class="zippy" zippy-title="myModel"></div>

指令

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();
            }
        }
    }
});

这似乎可行(尽管明显比 *proper* angularJS 变量绑定慢),但我认为必须有更好的方法来做到这一点。谁能解释一下这个问题?

【问题讨论】:

  • 只是好奇,我知道你最终不需要手动调用 $apply,但你为什么要同时绑定 blurchange?这不是多余的吗?如果没有,我很想知道与仅使用 keyup blur 有什么区别。
  • blurchange 是不同的,但我相信出于实际目的,keyupchange 在功能上是相似的。唯一的区别是,如果我以编程方式更改输入的值,使用change 会触发一个事件(输入的数据更改),而将change 留在外面会使这种更改不可见,除非它来自按键。请记住,这是“很久以前”的事了,我不知道我在用 angularJS 这个令人敬畏的野兽做什么;)

标签: javascript data-binding frameworks angularjs


【解决方案1】:

我不知道您为什么要手动触发$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>​

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
      }
    }
  });

更新 maxisam 是对的,您必须使用 ng-model 而不是像这样将变量与值绑定:

<input type="text" ng-model="title" style="width: 90%"/>

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

【讨论】:

  • 它没有,它只能以一种方式工作(就像在角度文档的例子中一样)。我正在尝试的是一种双向数据绑定方案 - 更改 $scope 值和指令的值更新,更改指令的值和 $scope 值更新。 LUCKY NOTE - 来自 angularJS 团队的 Brian Ford 在这里回答了这个问题:youtube.com/watch?feature=player_embedded&v=8_7K6bud5kw
  • @TiagoRoldão maxisam 是对的,我刚刚更新了我的帖子和 jsfiddle
  • 太棒了!关键字“title”虽然令人困惑..您能否将您的小提琴重命名为“innerTitle”,以便内部变量和外部变量(在指令中)之间的绑定清晰?
【解决方案2】:

您的意思是 this 之类的?

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

进行双向绑定的诀窍是 ng-model,它在 document 中声明:

ngModel 是告诉 Angular 进行双向数据绑定的指令。 它与输入、选择、文本区域一起工作。您可以轻松编写 你自己的指令也可以使用 ngModel。

<input type="text" ng-model="title" style="width: 90%"/>

【讨论】:

  • 你说得对,谢谢! :) 我更新了我的帖子并包含了更正的 jsfiddle!
【解决方案3】:

这是一种在指令中传递给回调参数的方法。控制器模板:

    <component-paging-select-directive
            page-item-limit="{{pageItemLimit}}"
            page-change-handler="pageChangeHandler(paramPulledOutOffThinAir)"
            ></component-paging-select-directive>

指令:

angular.module('component')
    .directive('componentPagingSelectDirective', [
        function( ) {
            return {
                restrict: 'E',
                scope: { 
                    // using the '=' for two way doesn't work
                    pageItemLimit:  '@', // the '@' is one way from controller
                    pageChangeHandler: '&'
                },
                controller: function($scope) {   
                    // pass value from this scope to controller method. 
                    // controller method will update the var in controller scope
                    $scope.pageChangeHandler({
                        paramPulledOutOffThinAir: $scope.pageItemLimit
                    })

                }, ...

在控制器中:

angular.module('...').controller(...
        $scope.pageItemLimit = 0; // initial value for controller scoped var

        // complete the data update by setting the var in controller scope 
        // to the one from the directive
        $scope.pageChangeHandler = function(paramPulledOutOffThinAir) {
            $scope.pageItemLimit = paramPulledOutOffThinAir;
        }

注意指令(以参数作为键的对象)、模板(指令中参数对象的“未包装”键)和控制器定义的函数参数的区别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    相关资源
    最近更新 更多