你能在创建AngularJS控制器时传递参数吗?
你能在创建AngularJS控制器时传递参数吗?
我有一个控制器负责与API通信,以更新用户的属性,如名称、电子邮件等。每个用户都有一个\'id\'
,当查看个人资料页面时,它从服务器传递。
我想将这个值传递给AngularJS控制器,以便它知道当前用户的API入口点。我尝试在ng-controller
中传递该值。例如:
function UserCtrl(id, $scope, $filter) { $scope.connection = $resource('api.com/user/' + id)
并在HTML中
其中{% id %}
打印从服务器发送的ID,但我得到错误。
什么是在创建控制器时传递值的正确方式?
admin 更改状态以发布 2023年5月22日
我加入得很晚,我不知道这是否是个好主意,但您可以在控制器函数中包括$attrs
,从而允许控制器使用在元素上提供的“参数”进行初始化,例如:
app.controller('modelController', function($scope, $attrs) { if (!$attrs.model) throw new Error("No model for modelController"); // Initialize $scope using the value of the model attribute, e.g., $scope.url = "http://example.com/fetch?model="+$attrs.model; }) Click here
再次声明,我不知道这是否是个好主意,但它似乎可行,并且是另一种替代方案。
注意:
这个答案是旧的。这只是一个实现期望结果的概念证明。然而,它可能不是最好的解决方案,如下面一些评论所述。我没有任何文档来支持或拒绝以下方法。请参阅下面的一些评论,以进一步讨论这个主题。
原始答案:
我回答了这个问题
是的,您绝对可以使用ng-init
和一个简单的init函数来这样做。
这是plunker上的例子
HTML
I am {{name}} {{id}}
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) }; });