0

I am trying to simplify my controller. So I tried to set variable to populate my checkbox list from outside controller. Is it possible?

Here is my current code http://jsfiddle.net/ilmansg/Lx37kr3e/1/

VIEW HTML

<div ng-controller="AdminEventsCtrl">
  <h1>Array 1</h1>
  <ul>
    <li ng-repeat="item in array1">
      <input type="checkbox" ng-model="formData.value1[item.value]" value="{{item.value}}" />
      {{item.text}}
    </li>
  </ul>

  <h1>Array 2</h1>
  <script>
    array2 = [{
    text: 'Option 1',
    value: 'opt1'
  }, {
    text: 'Option 2',
    value: 'opt2'
  }, {
    text: 'Option 3',
    value: 'opt3'
  }, {
    text: 'Option 4',
    value: 'opt4'
  }];
  </script>
  <ul>
    <li ng-repeat="item in array2">
      <input type="checkbox" ng-model="formData.value1[item.value]" value="{{item.value}}" />
      {{item.text}}
    </li>
  </ul>

  <pre>Array1= {{array1}}</pre>
  <pre>Array2= {{array2}}</pre>
</div>

SCRIPT JS

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

function AdminEventsCtrl($scope) {
  $scope.formData = {};

  $scope.array1 = [{
    text: 'Option 1',
    value: 'opt1'
  }, {
    text: 'Option 2',
    value: 'opt2'
  }, {
    text: 'Option 3',
    value: 'opt3'
  }, {
    text: 'Option 4',
    value: 'opt4'
  }];
}

2 Answers 2

1

No this is not possible because Angular would have no idea which scope to attach the array to. Here is a simplified solution to your problem of your controller being messy:

Have two arrays, one for each property text and value.

function AdminEventsCtrl($scope) {
  $scope.formData = {};
  $scope.array1 = [];

  var t = ['Option 1', 'Option 2', 'Option 3'];
  var v = ['opt1', 'opt2', 'opt3'];

  for(i=0;i<t.length;i++){
      $scope.array1.shift({text:t[i],value:v[i]});
  }

}

This may be a little more code, but it looks a lot less messy. It also allows you to easily add in new values.

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

1 Comment

hmm, if its only one variable indeed it wouldnt looks too messy. but if I have several checkbox list to be populated. It will still look like a mess :(
0

I end up making factory to hold all my arrays, then use that factory in my controller

Comments

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.