您可以在创建时将参数传递给 AngularJS 控制器吗? [英] Can you pass parameters to an AngularJS controller on creation?

查看:24
本文介绍了您可以在创建时将参数传递给 AngularJS 控制器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器负责与 API 通信以更新用户、姓名、电子邮件等的属性.每个用户都有一个 'id',当个人资料页面从服务器传递时被查看.

I have a controller responsible for communicating with an API to update properties of a user, name, email, etc. Each user has an 'id' which is passed from the server when the profile page is viewed.

我想将此值传递给 AngularJS 控制器,以便它知道当前用户的 API 入口点是什么.我试过在 ng-controller 中传递值.例如:

I would like to pass this value to the AngularJS controller so it knows what the API entry point is for the current user. I've tried passing the value in ng-controller. For example:

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

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

在 HTML 中

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

where {% id %} 打印从服务器发送的 id.但我收到错误.

where {% id %} print the id sent from the server. but I get errors.

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

What is the correct way to pass a value into a controller on its creation?

推荐答案

注意事项:

这个答案很旧.这只是关于如何实现预期结果的概念证明.但是,根据下面的一些评论,它可能不是最佳解决方案.我没有任何文件支持或拒绝以下方法.请参阅下面的一些评论以进一步讨论此主题.

This answer is old. This is just a proof of concept on how the desired outcome can be achieved. However, it may not be the best solution as per some comments below. I don't have any documentation to support or reject the following approach. Please refer to some of the comments below for further discussion on this topic.

原答案:

我回答了这个是的,您绝对可以使用 ng-init 和一个简单的 init 函数来做到这一点.

I answered this to Yes you absolutely can do so using ng-init and a simple init function.

这是 plunker

HTML

<!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)
  };


});

这篇关于您可以在创建时将参数传递给 AngularJS 控制器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆