Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind ngOptions to array outside of scope

Is it possible to bind ngOptions to a value outside of the $scope?

I have a set of enums that will be automatically rendered as javascript. These are currently not part of "the angular domain", but I want to bind a ngOptions to one of the arrays, and I would like to not have to copy the items into the scope manually.

The reason why I want this is because I have some HTML Helpers which renders the items automatically, so I want a very generic solution without the need of adding a lot of code to the controller. Is that possible?

var NS = NS || {};
NS.Sub  = NS.Sub || {};
// This is auto-generated:
NS.Sub.enums = {"deliveryStatus":[{"id":1,"label":"Delivered"},{"id":2,"label":"Expected"},{"id":4,"label":"Failed"}],"documentType":[{"id":0,"label":"Pdf"},{"id":1,"label":"Rtf"}]};


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

function MyCtrl($scope) {
    // If I copy the items to the scope it works.
    $scope.items = NS.Sub.enums.deliveryStatus;
    $scope.model = {}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="MyCtrl">
    <p>Not working SELECT (bound to array outside of scope)</p>
    <select ng-model="model.status" ng-options="item.label for item in NS.Sub.enums.deliveryStatus"></select>
  
    <p>Working SELECT (bound to array inside scope)</p>
    <select ng-model="model.status" ng-options="item.label for item in items"></select>
  </div>
</div>
like image 787
smoksnes Avatar asked Oct 18 '22 05:10

smoksnes


1 Answers

DEMO
You can attach NS to the $rootScope and you can then use it on any controller by just calling it directly NS

app.controller('MainController', function($rootScope){

    var vm = this;
    var NS = { Sub: { } };
    //you just need to do this once
    NS.Sub.enums = {"deliveryStatus":[{"id":1,"label":"Delivered"},{"id":2,"label":"Expected"},{"id":4,"label":"Failed"}],"documentType":[{"id":0,"label":"Pdf"},{"id":1,"label":"Rtf"}]};
    $rootScope.NS = NS;
});

Simply use it like

<select ng-model="model.status" ng-options="item.label for item in NS.Sub.enums.deliveryStatus"></select>
like image 71
Louie Almeda Avatar answered Oct 20 '22 23:10

Louie Almeda