javascript - 无法在组件之间绑定一些数据?
问题描述
我正在计算/构建指令(组件)中的 javascript 对象,我想将它传递给另一个组件。
在我的例子中,我指的是 heroList.js(它是源组件)中的英雄列表,我想将 passingObject 传输到 someOtherTabPage.js(它是目标组件)。
这是我的 plunk的链接。你能帮我解决这个问题吗,我不知道将passingObject绑定到我的两个组件之间有什么问题?
(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);
解决方案
要使用相同的架构实现您所需要的,您可以使用 $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>
推荐阅读
- r - 如何在 R 中获取已加载库的安装位置?
- python - 在某些情况下,使用正则表达式将文本文件中的输入读入字典
- c - 为什么这段代码在使用在线编译器和 turbo ide 时显示不同的输出?
- javascript - nodejs - 如何从异步函数中获取返回
- java - 将 Keycloak 与 pgbouncer 一起使用
- python - 如何使用列表的元素作为键并将矩阵中的相应数字作为值来生成字典?
- sql - PL/SQL 游标的问题
- c++ - 类全局随机数生成器
- python - Python:Selenium Chrome 驱动程序打开空白页--已解决--
- javascript - 如何增量切片数组