javascript - Sử dụng dấu gạch dưới bên trong các controller của Angular
Làm thế nào để tôi sử dụng thư viện underscore bên trong các bộ điều khiển AngularJS?
Trong bài đăng này: AngularJS limitTo theo 2 bản ghi cuối, ai đó đã gợi ý gán một biến _ vào rootScope để thư viện có thể được sử dụng trong tất cả các scope trong ứng dụng.
Nhưng tôi không rõ nên thực hiện nó ở đâu. Ý tôi là nó có nên được đưa vào khai báo mô-đun ứng dụng không? Ví dụ:
var myapp = angular.module('offersApp', [])
.config(['$rootScope', function($rootScope) { }
Nhưng rồi tôi tải thư viện underscore ở đâu? Tôi chỉ có trên trang chỉ mục của mình directive ng-app và tham chiếu script đến cả thư viện angular-js và underscore?
index.html:
<head>
</head>
<body ng-app="offersApp">
...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="scripts/vendor/angular.js"></script>
<script src="scripts/vendor/underscore.js"></script>
...
Làm thế nào để tôi đạt được điều này?
Câu trả lời #1
Khi bạn bao gồm Underscore, nó tự gắn vào đối tượng window, do đó có sẵn trên toàn cầu.
Vì vậy bạn có thể sử dụng nó từ mã Angular như hiện tại.
Bạn cũng có thể đóng gói nó trong một dịch vụ hoặc một nhà máy, nếu bạn muốn nó được tiêm vào:
var underscore = angular.module('underscore', []);
underscore.factory('_', ['$window', function($window) {
return $window._; // assumes underscore has already been loaded on the page
}]);
Và sau đó bạn có thể yêu cầu _ trong mô-đun ứng dụng của bạn:
// Declare it as a dependency of your module
var app = angular.module('app', ['underscore']);
// And then inject it where you need it
app.controller('Ctrl', function($scope, _) {
// do stuff
});
Câu trả lời #2
Tôi đã thực hiện đề xuất của @satchmorun tại đây: https://github.com/andresesfm/angular-underscore-module
Để sử dụng nó:
Hãy chắc chắn rằng bạn đã thêm underscore.js vào dự án của mình
<script src="bower_components/underscore/underscore.js">Lấy nó:
bower install angular-underscore-moduleThêm angular-underscore-module.js vào tệp chính của bạn (index.html)
<script src="bower_components/angular-underscore-module/angular-underscore-module.js"></script>Thêm module như một phụ thuộc trong định nghĩa Ứng dụng của bạn
var myapp = angular.module('MyApp', ['underscore'])Để sử dụng, thêm làm phụ thuộc được tiêm vào Controller/Service của bạn và nó sẵn sàng để sử dụng
angular.module('MyApp').controller('MyCtrl', function ($scope, _) { ... //Use underscore _.each(...); ...
Câu trả lời số 3
Tôi dùng cái này:
var myapp = angular.module('myApp', [])
// allow DI for use in controllers, unit tests
.constant('_', window._)
// use in views, ng-repeat="x in _.range(3)"
.run(function ($rootScope) {
$rootScope._ = window._;
});
Xem https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection khoảng giữa trang để biết thêm thông tin về run.
