我有一个控制器负责与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-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.module('myModule').directive('user', function ($filter) {
return {
link: function (scope, element, attrs) {
$scope.connection = $resource('api.com/user/' + attrs.userId);
}
};
});
<user user-id="{% id %}"></user>
如果你不需要访问包装范围内的变量,可以使用这个:
angular.module('myModule').directive('user', function ($filter) {
return {
scope: {
userId: '@'
},
link: function (scope, element, attrs) {
$scope.connection = $resource('api.com/user/' + scope.userId);
}
};
});
<user user-id="{% id %}"></user>
对于我的特定用例,我真的不喜欢这里的任何解决方案,所以我想我应该发布我所做的,因为我在这里没有看到它。
我只是想在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。
如果ng-init不是用来将对象传递到$scope,你可以编写自己的指令。这就是我得到的结果:
http://jsfiddle.net/goliney/89bLj/
Javasript:
var app = angular.module('myApp', []);
app.directive('initData', function($parse) {
return function(scope, element, attrs) {
//modify scope
var model = $parse(attrs.initData);
model(scope);
};
});
function Ctrl1($scope) {
//should be defined
$scope.inputdata = {foo:"east", bar:"west"};
}
Html:
<div ng-controller="Ctrl1">
<div init-data="inputdata.foo=123; inputdata.bar=321"></div>
</div>
但是我的方法只能修改已经在控制器中定义的对象。