0

I created a directive to handle form input groups. Each input needs to be bound to a root scope variable. I set up a factory to store the variables so that I can use them in the main controller and directive.

So far, I've gotten as far as to have the data populate the form fields (all of the same data in every field). But I'm doing that by specifying the field name. In order to have each instance of the directive show different data, I can send the name of the field to which it should bind, but it throws an error if I use it in ng-model.

Also, even when I hard-code the field in, it's only a one-way binding.

    var app = angular.module('myApp', []);
    app.controller('mainCtl', function($scope, sharedData){
        $scope.otherdata = "main scope";$scope.test = sharedData.data1;
    }).service('sharedData', function(){
        this.data1 = 600;
      this.data2 = 700;
    }).directive('myDir', function(sharedData){
        return {
      restrict: 'E',
        replace: 'true',
        templateUrl: 'my-dir',
        scope: {
        bindTo: '=',
            showMe: '='
        },
        link: function(scope, element, attrs){
            scope.data1 = sharedData.data1;
          scope.data2 = sharedData.data2;
        }
      };

Shortened sample here: https://jsfiddle.net/wkaskie/najnkga4/12/ In the fiddle, I have it to where there is a one-way binding to data1. I need to pass in a variable to indicate to which field each input should be bound.

Wayne F. Kaskie
  • 3,257
  • 5
  • 33
  • 43

1 Answers1

0

UPDATE Good news, after 12 hours of researching and testing, I came up with a solution.

  1. Consider the controllers more. I created a new controller to handle the subset of data and attached it to the directive.

    app.controller('subCtl', function($scope, sharedData){ this.sData = sharedData; }).directive('myDir', function(sharedData){ return { restrict: 'E', replace: 'true', templateUrl: 'my-dir', bindToController: true, controller:'subCtl', controllerAs: 'sub', //...

  2. Right on the dot. Much advise I've found was to use dot notation, so I did and that fixed most of the binding issues. In other words, instead of binding the specific data variables I bound the whole daggone object, which included the data points. from: scope.data1 = sharedData.data1; to: scope.allData = sharedData; (which includes sharedData.data1, sharedData.data2)

  3. Remember the brackets. Also, my big wish was to be able to tell each instance of my directive to model the input field off of a different data field. Using bracket notation helped to clear this up. The concept was a simple as passing a basic JavaScript expression to ng-model.

I've updated the fiddle to demo the changes.

Wayne F. Kaskie
  • 3,257
  • 5
  • 33
  • 43