你可以传递参数上建立一个AngularJS控制器? [英] Can you pass parameters to an AngularJS controller on creation?
问题描述
我负责与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.
我想,以便它知道API入口点是什么为当前用户该值传递给AngularJS控制器。我试图传递值 NG-控制器
。例如:
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 %})">
其中, {%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
和一个简单的初始化函数。
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屋!