将ngOptions绑定到范围之外的数组

smo*_*nes 5 javascript angularjs

是否可以绑定ngOptions$scope?之外的值?

我有一组枚举,将自动呈现为javascript.这些目前不是"角度域"的一部分,但我想将其绑定ngOptions到其中一个数组,我不想手动将项目复制到范围中.

我想要这个的原因是因为我有一些自动渲染项目的HTML Helpers,所以我想要一个非常通用的解决方案而不需要向控制器添加大量代码.那可能吗?

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 = {}
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Lou*_*eda 2

DEMO
您可以附加NS$rootScope,然后只需直接调用它就可以在任何控制器上使用它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;
});
Run Code Online (Sandbox Code Playgroud)

只需像这样使用它

<select ng-model="model.status" ng-options="item.label for item in NS.Sub.enums.deliveryStatus"></select>
Run Code Online (Sandbox Code Playgroud)