我有一个控制器负责与API通信,以更新用户的属性,名称,电子邮件等。每个用户都有一个“id”,当查看配置文件页面时,这个“id”从服务器传递过来。

我想把这个值传递给AngularJS控制器,这样它就知道当前用户的API入口点是什么。我试着在ng-controller中传递这个值。例如:

function UserCtrl(id, $scope, $filter) {

$scope.connection = $resource('api.com/user/' + id)

在HTML中

<body ng-controller="UserCtrl({% id %})">

其中{% id %}打印从服务器发送的id。但是会有错误。

在创建控制器时将值传递给控制器的正确方法是什么?


当前回答

如果使用angular-ui-router,那么这是正确的解决方案:https://github.com/angular-ui/ui-router/wiki#resolve

基本上,在控制器实例化之前声明一组要“解析”的依赖项。你可以为你的每个“状态”声明依赖关系。然后将这些依赖项传递到控制器的“构造函数”中。

其他回答

如果使用angular-ui-router,那么这是正确的解决方案:https://github.com/angular-ui/ui-router/wiki#resolve

基本上,在控制器实例化之前声明一组要“解析”的依赖项。你可以为你的每个“状态”声明依赖关系。然后将这些依赖项传递到控制器的“构造函数”中。

还有另一种方法将参数传递给控制器,即将$routeParams注入到你的控制器中,然后使用这里描述的url参数,在AngularJS中读取查询参数的最简洁的方法是什么?

就像@akonsu和Nigel Findlater建议的那样,你可以用$routeParams读取url, url是index.html#/user/:id。Id并在控制器中使用它。

你的应用程序:

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

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/:type/:id', {templateUrl: 'myView.html', controller: 'myCtrl'});
}]);

资源服务

app.factory('MyElements', ['$resource', function($resource) {
     return $resource('url/to/json/:type/:id', { type:'@type', id:'@id' });
}]);

控制器

app.controller('MyCtrl', ['$scope', '$routeParams', 'MyElements', function($scope, $routeParams, MyElements) {
    MyElements.get({'type': $routeParams.type, "id": $routeParams.id }, function(elm) {
        $scope.elm = elm;
    })
}]);

然后,根据id在视图中可以访问elm。

注:

这个答案已经过时了。这只是一个关于如何实现预期结果的概念证明。然而,根据下面的一些评论,这可能不是最好的解决方案。我没有任何文档来支持或拒绝以下方法。请参考下面的一些评论,以进一步讨论这个主题。

最初的回答:

我回答了这个问题 是的,你完全可以使用ng-init和一个简单的init函数来做到这一点。

这是它在plunker的例子

超文本标记语言

<!DOCTYPE html>
<html ng-app="angularjs-starter">
  <head lang="en">
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script src="app.js"></script>
  </head>  
  <body ng-controller="MainCtrl" ng-init="init('James Bond','007')">
    <h1>I am  {{name}} {{id}}</h1>
  </body>
</html>

JavaScript

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {

  $scope.init = function(name, id)
  {
    //This function is sort of private constructor for controller
    $scope.id = id;
    $scope.name = name; 
    //Based on passed argument you can make a call to resource
    //and initialize more objects
    //$resource.getMeBond(007)
  };


});

这个问题很老了,但我挣扎了很长时间,试图找到一个适合我需要的答案,但并不容易找到。我相信我下面的解决方案比目前接受的解决方案要好得多,也许是因为angular在最初提出这个问题时增加了功能。

简单的回答,使用模块。Value方法允许您将数据传递给控制器构造函数。

看我的活塞

我创建了一个模型对象,然后将它与模块的控制器相关联,引用它的名称为'model'

HTML / JS

  <html>
  <head>
    <script>
      var model = {"id": 1, "name":"foo"};

      $(document).ready(function(){
        var module = angular.module('myApp', []);
        module.value('model', model);
        module.controller('MyController', ['model', MyController]);
        angular.bootstrap(document, ['myApp']);
      });

      function confirmModelEdited() {
        alert("model name: " + model.name + "\nmodel id: " + model.id);
      }
    </script>

  </head>
  <body >
      <div ng-controller="MyController as controller">
        id: {{controller.model.id}} <br>
        name: <input ng-model="controller.model.name"/>{{controller.model.name}}
        <br><button ng-click="controller.incrementId()">increment ID</button>
        <br><button onclick="confirmModelEdited()">confirm model was edited</button>
    </div>
  </body>

</html>

然后,我的控制器中的构造函数接受一个具有相同标识符“model”的参数,然后它可以访问这个标识符。

控制器

function MyController (model) {
  this.model = model;
}

MyController.prototype.incrementId = function() {
  this.model.id = this.model.id + 1;
}

注:

我使用手动初始化bootstrapping,这允许我在将模型发送给angular之前初始化它。这对于现有的代码来说效果更好,因为你可以等待相关数据的设置,只在你想要的时候按需编译应用程序的angular子集。

在plunker中,我添加了一个按钮来提醒最初在javascript中定义并传递给angular的模型对象的值,只是为了确认angular真正引用了模型对象,而不是复制它并使用副本。

在这一行:

module.controller('MyController', ['model', MyController]);

我将MyController对象传递到模块中。控制器函数,而不是声明为内联函数。我认为这可以让我们更清楚地定义控制器对象,但Angular文档倾向于内联,所以我认为有必要澄清一下。

我使用“controller as”语法并将值分配给MyController的“this”属性,而不是使用“$scope”变量。我相信使用$scope也能很好地工作,控制器赋值看起来是这样的:

module.controller('MyController', ['$scope', 'model', MyController]);

控制器构造函数会有这样的签名:

function MyController ($scope, model) {

如果出于任何原因,您还可以将此模型作为第二个模块的值附加,然后将其作为依赖项附加到您的主模块。

我相信他的解决办法比目前公认的好得多,因为

传递给控制器的模型实际上是一个javascript对象,而不是要计算的字符串。它是对对象的真实引用,对它的更改会影响对该模型对象的其他引用。 Angular说,接受的答案使用ng-init是一种误用,而这个解决方案不会这样做。

The way Angular seems to work in most all other examples I've seen has the controller defining the data of the model, which never made sense to me, there is no separation between the model and the controller, that doesn't really seem like MVC to me. This solution allows you to really have a completely separate model object which you pass into the controller. Also of note, if you use the ng-include directive you can put all your angular html in a separate file, fully separating your model view and controller into separate modular pieces.