Erma
Erma

Reputation: 387

AngularJS: 2 way binding in directive

I have a directive as follows,

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

And a template:

  <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 consists of

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

My problem is that, I can a create a template with ng-repeat, but after binding, when I change something in the template, it doesn't change elsewhere. How can I get the modified value?

Upvotes: 0

Views: 220

Answers (2)

Erma
Erma

Reputation: 387

Got it working after adding 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>

Upvotes: 1

ababashka
ababashka

Reputation: 2101

You should to change your $watch definition:

$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

Upvotes: 0

Related Questions