AngularJS:指令中的2路绑定

时间:2015-03-10 12:25:00

标签: angularjs data-binding angularjs-directive

我有如下指令,

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

    myApp.directive("checkTextCombo", [
      "$compile", function($compile) {
        return {
          restrict: "E",
          replace: true,
          scope: {
            source: '@',
         },
         link: function(scope, element, attrs) {
           scope.rows = eval('(' + scope.source + ')');
         },
          templateUrl: "../templates/check-text-combo/check-text-combo.html",
          controller: function($scope){
            $scope.$watch('$scope.rows', function() {
              console.log($scope.rows);
            });
          }
        };
      }
    ]);

一个模板:

  <div ng-repeat="row in rows">
    <input type="checkbox" ng-checked="row.checked"/> <label value="{{row.label}}">{{row.label}}</label><input type="textbox" value="{{row.value}}" ng-disabled="!row.checked"/>
  </div>

index.html

组成
   <check-text-combo source="[{'value':'varsh','label':'name','checked': true}, {'value':'bij','label':'name','checked': false}]"></check-text-combo>

我的问题是,我可以使用ng-repeat创建一个模板,但在绑定后,当我在模板中更改某些内容时,它不会在其他地方更改。如何获得修改后的值?

2 个答案:

答案 0 :(得分:1)

添加ng-model

后工作正常
<div ng-repeat="row in rows">
  <input type="checkbox" ng-checked="row.checked" ng-model="row.checked"/> <label value="{{row.label}}">{{row.label}}</label><input type="textbox" value="{{row.value}}" ng-model="row.value" ng-disabled="!row.checked"/>
</div>

答案 1 :(得分:0)

您应该更改$watch定义:

$scope.$watch('rows', function() {
//              ^
//             Here
//    rows instead of $scope.rows
  console.log($scope.rows);
}, true);
//  ^
//and here
// third parameter to true - observed variable is an Object