我有一个控制器负责与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。但是会有错误。
在创建控制器时将值传递给控制器的正确方法是什么?
对于我的特定用例,我真的不喜欢这里的任何解决方案,所以我想我应该发布我所做的,因为我在这里没有看到它。
我只是想在ng-repeat循环中使用一个更像指令的控制器:
<div ng-repeat="objParameter in [{id:'a'},{id:'b'},{id:'c'}]">
<div ng-controller="DirectiveLikeController as ctrl"></div>
</div>
现在,为了在每个DirectiveLikeController中创建时访问objParameter(或在任何时候获得最新的objParameter),我所需要做的就是注入$scope并调用$scope.$eval('objParameter'):
var app = angular.module('myapp', []);
app.controller('DirectiveLikeController',['$scope'], function($scope) {
//print 'a' for the 1st instance, 'b' for the 2nd instance, and 'c' for the 3rd.
console.log($scope.$eval('objParameter').id);
});
我看到的唯一缺点是它要求父控制器知道参数名为objParameter。
我发现从$routeProvider传递变量很有用。
例如,你在多个屏幕上使用一个控制器MyController,在里面传递一些非常重要的变量“mySuperConstant”。
使用这个简单的结构:
Router:
$routeProvider
.when('/this-page', {
templateUrl: 'common.html',
controller: MyController,
mySuperConstant: "123"
})
.when('/that-page', {
templateUrl: 'common.html',
controller: MyController,
mySuperConstant: "456"
})
.when('/another-page', {
templateUrl: 'common.html',
controller: MyController,
mySuperConstant: "789"
})
MyController:
MyController: function ($scope, $route) {
var mySuperConstant: $route.current.mySuperConstant;
alert(mySuperConstant);
}
注:
这个答案已经过时了。这只是一个关于如何实现预期结果的概念证明。然而,根据下面的一些评论,这可能不是最好的解决方案。我没有任何文档来支持或拒绝以下方法。请参考下面的一些评论,以进一步讨论这个主题。
最初的回答:
我回答了这个问题
是的,你完全可以使用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)
};
});
我对此很晚了,我不知道这是否是一个好主意,但你可以在控制器函数中包括$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;
})
<div ng-controller="modelController" model="foobar">
<a href="{{url}}">Click here</a>
</div>
同样,不知道这是否是一个好主意,但它似乎有效,是另一种选择。