我在指令(组件)中计算/构建javascript对象,我想将它传递给另一个组件。
就我而言,我指的是heroList.js(源组件)中的英雄列表,我想将passingObject传递给someOtherTabPage.js(这是目标组件)
这是我的link。你能帮忙解决这个问题吗,我没有把passObject绑定到我的两个组件之间有什么不对吗?
(function(angular) {
'use strict';
function someOtherTabPageController($scope) {
//do some work with the passingObject
alert(JSON.stringify(passingObject));
}
angular.module('heroApp').component('someOtherTabPage', {
templateUrl: 'someOtherTabPage.html',
controller: someOtherTabPageController,
bindings :{
passingObject: '='
}
});
})(window.angular);
答案 0 :(得分:1)
要使用相同的架构实现所需,您可以使用$ rootScope在控制器之间传递数据。这是更新的代码:
(function(angular) {
'use strict';
function someOtherTabPageController($scope,$rootScope) {
var ctrl = this;
//do some work with the passingObject
alert($rootScope.passingObject);
}
angular.module('heroApp').component('someOtherTabPage', {
templateUrl: 'someOtherTabPage.html',
controller: someOtherTabPageController,
bindings :{
passingObject: '='
}
});
})(window.angular);
(function(angular) {
'use strict';
function HeroListController($scope, $element, $attrs,$rootScope) {
var ctrl = this;
// This would be loaded by $http etc.
ctrl.list = [
{
name: 'Superman',
location: ''
},
{
name: 'Batman',
location: 'Wayne Manor'
}
];
ctrl.create = function(hero) {
ctrl.list.push(angular.copy(hero));
};
ctrl.updateHero = function(hero, prop, value) {
hero[prop] = value;
};
ctrl.deleteHero = function(hero) {
var idx = ctrl.list.indexOf(hero);
if (idx >= 0) {
ctrl.list.splice(idx, 1);
}
};
$scope.passingObject = ctrl.list;
$rootScope.passingObject = ctrl.list;
}
angular.module('heroApp').component('heroList', {
templateUrl: 'heroList.html',
controller: HeroListController,
bindings: {
onCreate: '&'
}
});
})(window.angular);
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-heroComponentTree-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="index.js"></script>
<script src="heroList.js"></script>
<script src="heroDetail.js"></script>
<script src="editableField.js"></script>
<script src="someOtherTabPage.js"></script>
</head>
<body ng-app="heroApp">
<hero-list></hero-list>
<some-other-tab-page></some-other-tab-page>
</body>
</html>
答案 1 :(得分:0)
我认为在控制器中绑定passingObject
之后,你应该通过this
关键字
function someOtherTabPageController($scope) {
var ctrl = this;
//do some work with the passingObject
alert(JSON.stringify(ctrl.passingObject));
}
你可以在HeroDetailController中的heroDetail.js中看到你的示例插件中应用的相同原理
编辑以解决最后评论:'传递对象未定义'
我的第一个猜测是组件未在实例化中传递passingObject
。正确的方式如下:
<some-other-tab-page passing-object="someObjectHere"></some-other-tab-page>