javascript - 将环境细节注入(inject) AngularJS Controller

标签 javascript angularjs

让我们以 AngularJS tutorial 中的示例为例

function PhoneListCtrl($scope, $http) {
   $http.get('phones/phones.json').success(function(data) {
      $scope.phones = data;
   });

   $scope.orderProp = 'age';
}

//PhoneListCtrl.$inject = ['$scope', '$http'];

现在,假设我不想对 url 'phones/phones.json' 进行硬编码,而是更喜欢托管此 Controller 的页面来注入(inject)它,正确的方法应该是什么在 Angular JS 中做同样的事情?

最佳答案

有很多方法可以做到这一点...最简单的方法就是使用 $window,这样您就可以注入(inject) $window 服务,这基本上就是全局 $被注入(inject)的窗口。然后您可以将这些路径注册为 window.path = 'whatever.json'; 就可以了:

window.path = 'some/path.json';

function PhoneListCtrl($scope, $http, $window) {
   $http.get($window.path).success(function(data) {
      $scope.phones = data;
   });

   $scope.orderProp = 'age';
}

一种更高级的方法是创建一个模块,其中包含您注入(inject)到应用中的服务,在这种情况下,每个页面都会有自己的模块:

 //create your module.
 angular.module('configData', [])
   .factory('pathService', function () {
        return {
           path: 'some/path.json'
        };
   });

//then inject it into your app
var app = angular.module('myApp', ['configData']);

app.controller('PhoneListCtrl', function($scope, $http, pathService) {
   $http.get(pathService.path).success(function(data) {
       $scope.phones = data;
   });

   $scope.orderProp = 'age';
});

当然,您可以在两者之间做任何事情。我建议采用最易于维护但仍易于测试的路径。

关于javascript - 将环境细节注入(inject) AngularJS Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13717670/

相关文章:

javascript - rails - 如何将 onsubmit 与 form_tag 一起使用

angularjs - Angular Controller As Syntax-no 方法 '$watchCollection'

javascript - 在 AngularJS 服务中共享数据

javascript - 使用像 angularjs 这样的框架对可访问性有什么影响?

javascript - angular-ui-router 更改 $state.go() 上的数据对象

javascript - 为什么 jQuery 的 .val() 返回 null?

javascript - Chart.js 2.1.6 每个部分的背景颜色

javascript - 我如何将这个 toggleClass 函数创建为 AngularJS 指令?

javascript - AngularJS 代码不工作

c# - 如何使用angularJs将Json结果放入表格