且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AngularJS 指令中的两种数据绑定方式

更新时间:2023-02-26 22:55:16

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

I don't know why you are triggering the $apply method manually because you actually don't need it.

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

I edited the example you used from the Angular page and included the input. It works for me: 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 而不是像这样将变量与值绑定:

UPDATE maxisam is right, you have to use ng-model instead of binding the variable against the value like so:

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

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