0

I'm a newbie to Angular. Enjoy the fun of learning new things currently.

Here is my intention - I would like to have a list of input boxes. And then I want to get the combined string value from user input. The count of input boxes is passed from the custom directive's parent controller. After I get the combined value I also need to pass it back to its parent scope.

Here is where I am so far.

angular.module('starter.directives', [])
  .directive('userInput', function($compile) {
    return {
      //      templateUrl: 'templates/user-input-singlebox.html',
      template: '<div></div>',
      restrict: 'E',
      scope: {
        records: '='

      },
      //controller needs to serve as API
      controller: function($scope) {

      },
      link: function($scope, $element, $attrs) {
        $scope.inputCount = $scope.$parent.userInputStaticCount;
        var records = [];

        $scope.getInputBoxNum = function() {
          return new Array($scope.inputCount);
        };


        $scope.userInputBoxRecordList = "hello";

        $scope.getUserInput = function() {
          //return a combined string of value from input box index 0 to input box index n-1;
        }
        var html = '<div ng-repeat="i in getInputBoxNum() track by $index"><input id="{{$index+1}}" type="text" ng-model="userInputBoxRecordList" name="box"' + 'style="background-color:beige; border:1px solid black;"></div>';
        var e = $compile(html)($scope);
        $element.replaceWith(e);
      }
    }

  });
  1. However, I'm assigning a unique id to each input box, I wonder if there is a better way like using an ng-model to get the userInput() function work.
  2. I want to dynamically generate a list of user input boxes. Currently I put all the code in post link function. I believe I can write ONE input box in a template and then generate a list of boxes. However didn't figure it out by self. Any hints?
4
  • do you need isolate scope? Commented Oct 27, 2015 at 21:52
  • @TimCodes not necessarily. Any ideas? Commented Oct 27, 2015 at 22:12
  • think so let put a plunk togather Commented Oct 27, 2015 at 22:30
  • got something working. sharing scope with parent might be easier Commented Oct 27, 2015 at 22:40

1 Answer 1

1

You could use an array of objects instead of an array of items. Then on each object you can have text property to keep track of the value of the input field by binding the text property using ng-model. than have a function that iterates through your array and concats the text to gather. Hope this works for you

// js

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

app.controller('MainCtrl', function($scope) {

  $scope.combinedString = '';
  $scope.InpustStaticCount =5 ;

  $scope.getCombinedString = function(){

    $scope.items.forEach(function(el){

          $scope.combinedString += el.text + ", ";

          console.log($scope.combinedString);
    });
  }

});


app.directive('userInput', function($compile) {
    return {

      templateUrl: 'dir.html',
      restrict: 'E',
      scope:false, 
      //controller needs to serve as API
      controller: function($scope) {


      },
      link: function($scope, $element, $attrs) {

        $scope.items = [];

        for(var i = 0; i < $scope.InpustStaticCount; i ++ ){

          $scope.items.push({text: ''});        }



      }
    }

  });

// main html 
  <body ng-controller="MainCtrl">
    <p>Enter data in input boxes then press button</p>
    <user-input></user-input>
    <button class="btn btn-info" ng-click="getCombinedString()">Get Combined String</button>
    <div class="panel panel-info">
      <div class="panel-heading">Combined String</div>
      <div class="panel-body">{{combinedString}}</div>
    </div>
  </body>

//directive html 
<div ng-repeat = "item in items track by $index">
  <input id="{{$index+1}}" type="text" ng-model='item.text' > {{$index}} {{item.text}}
</div>

Here is a directive that uses isolate scope instead of shared

 app.directive('userInputIsolate', function($compile) {
    return {

      templateUrl: 'dir.html',
      restrict: 'E',
      scope:{

        inpuststaticount : "=",
        items: '='
      }, 
      //controller needs to serve as API
      controller: function($scope) {



      },
      link: function($scope, $element, $attrs) {

        console.log($scope.inpuststaticount)

        for(var i = 0; i < $scope.inpuststaticount; i ++ ){

          $scope.items.push({text: ''});        }



      }
    }

  });
   app.controller('MainCtrl', function($scope) {


  $scope.secondcombinedString = '';
  $scope.InpustStaticCount =5 ;

   $scope.secondItems = [];

    $scope.getCombinedStringIsolate = function(){

    $scope.secondItems.forEach(function(el){

          $scope.secondcombinedString += el.text + ", ";

          console.log($scope.combinedString);
    });
  }

});

// main html
 <user-input-isolate inpuststaticount= 'InpustStaticCount' items = 'secondItems'  ></user-input-isolate>

plunk: http://plnkr.co/edit/RrhZXbHyoGQ4cb1WirZS?p=preview

Sign up to request clarification or add additional context in comments.

5 Comments

This is exactly what I want, just one quick thing. I only want the items in your directive html to be exposed to parent scope, not entirely false. I thought something like this should work: items: '='. But I tried it out, and failed. Any comments?
you can use isolate scope if you want just increaes complexity a bit .Give me a sec.
check plunk out now, added a second directive that uses isoalte scope
Thanks for your code and they work so nicely. You deserve the points!
Just one quick thing, hope you have some ideas. For non-scope directive version, if I want to use $scope.$watch to watch the items array changes(deep watch), once all the boxes are filled, an alert box pop up. I can achieve this in directive link function, but not controller(items is shown as undefined)... Any thoughts?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.