我有一个控制器负责与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。但是会有错误。
在创建控制器时将值传递给控制器的正确方法是什么?
就像@akonsu和Nigel Findlater建议的那样,你可以用$routeParams读取url, url是index.html#/user/:id。Id并在控制器中使用它。
你的应用程序:
var app = angular.module('myApp', [ 'ngResource' ]);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/:type/:id', {templateUrl: 'myView.html', controller: 'myCtrl'});
}]);
资源服务
app.factory('MyElements', ['$resource', function($resource) {
return $resource('url/to/json/:type/:id', { type:'@type', id:'@id' });
}]);
控制器
app.controller('MyCtrl', ['$scope', '$routeParams', 'MyElements', function($scope, $routeParams, MyElements) {
MyElements.get({'type': $routeParams.type, "id": $routeParams.id }, function(elm) {
$scope.elm = elm;
})
}]);
然后,根据id在视图中可以访问elm。
This is an expansion of @Michael Tiller's excellent answer. His answer works for initializing variables from the view by injecting the $attrs object into the controller. The problem occurs if the same controller is called from $routeProvider when you navigate by routing. Then you get injector error Unknown provider : $attrsProvider because $attrs is only available for injection when the view is compiled. The solution is to pass the variable (foo) through $routeParams when initializing controller from route and by $attrs when initializing controller from view. Here's my solution.
从路线
$routeProvider.
when('/mypage/:foo', {
templateUrl: 'templates/mypage.html',
controller: 'MyPageController',
caseInsensitiveMatch: true,
resolve: {
$attrs: function () {
return {};
}
}
});
它处理一个url,如'/mypage/bar'。正如你所看到的,foo是通过url param传递的,我们为$attrs提供了一个空白对象,因此注入器没有错误。
从视图
<div ng-controller="MyPageController" data-foo="bar">
</div>
现在是控制器
var app = angular.module('myapp', []);
app.controller('MyPageController',['$scope', '$attrs', '$routeParams'], function($scope, $attrs, $routeParams) {
//now you can initialize foo. If $attrs contains foo, it's been initialized from view
//else find it from $routeParams
var foo = $attrs.foo? $attrs.foo : $routeParams.foo;
console.log(foo); //prints 'bar'
});
如果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>
但是我的方法只能修改已经在控制器中定义的对象。