在其他位置显示对象中的数据
Show data from object somewhere else
所以我在项目中使用了当前的angular,但在添加动态内容时遇到了问题。
因此,我创建了一个带有ng repeat的列表,当我点击它时,我会从我点击的特定项目中获得所有信息,并将其添加到新的范围项目中。
$scope.click = function() {
$scope.personData = this.person;
};
现在我想在特定的地方打印{{personData.name}},它在元素中运行良好,但当我想在元素之外的其他地方使用它时(例如在NG视图中的另一个页面中),我将完全相同的控制器链接到它,在我的想法中,我可以访问相同的数据,它不会在我的页面上更新。
有
app.controller('showDataController', function(jsonData, $scope, infoService) {
jsonData.async().then(function(response) {
$scope.data = response;
$scope.click = function() {
infoService.setPersonData(this.person);
};
});
});
app.service('infoService', function() {
var people = {};
function setPersonData(person) {
people[person.name] = person; // assuming person is an object
return people;
}
});
这是因为在每次重新加载视图/状态时,控制器都会被重新加载,因此没有对该范围的引用$scope指的是当前控制器。要在应用程序中传递对象,请创建一个服务或工厂,该服务或工厂可以使用get和set方法存储和检索这些信息。然后您添加项目的控制器代码可以是:
$scope.click = function() {
myService.setPersonData(this.person);
};
用于检索:
$scope.personData = myService.getPersonData(this.person.name); // a reference to that person is needed
您的服务设置和获取方法可能看起来像:
var people = {};
function setPersonData(person) {
people[person.name] = person; // assuming person is an object
return people;
}
function getPersonData(name) {
return people[personName];
}
更新
根据问题中的更新代码,请尝试以下操作:
app
.service('infoService', infoService)
.controller('showDataController', showDataController);
showDataController.$inject = ['jsonData', '$scope', 'infoService']; // this makes your code minification safe
function infoService() {
var people = {};
// returns an object with references to the methods defined in the service - aka the Revealing Module Pattern
return {
setPersonData: setPersonData
//getPersonData: getPersonData (comment out once this method is declared below)
};
function setPersonData(person) {
people[person.name] = person; // assuming person is an object
return people;
}
});
function showDataController(jsonData, $scope, infoService) {
jsonData.async().then(function(response) {
$scope.data = response;
$scope.click = function() {
infoService.setPersonData(this.person);
};
});
});
注意:通常我会把应用程序的不同组件放在不同的文件中。一个好的风格指南是https://github.com/johnpapa/angular-styleguide但也有其他类似的https://github.com/toddmotto/angularjs-styleguide
相关文章:
- 在控制器和数据对象之间同步数据
- AngularJs指令,该指令创建内部有数据对象的新指令
- 从数据对象数组创建折线图
- Vue.js 数据对象不适用于某些 lodash 函数
- 无法获取带有 .data(el,'dataname').sublev 的数据对象
- React.js+Flux-正确初始化存储中的数据对象
- 如何调用另一个js文件中的函数或触发一个自定义事件,该事件将参数作为Jquery中的数据对象传递
- Meteor模板数据对象可防止javascript事件触发
- 我该如何访问由gullow灰质插件创建的数据对象(当使用nunjucks编译html文件时)
- 如何使用javascript数据对象?如何通过变量访问条目
- Knockout:为许多数据对象绑定模板引导模式
- 如何将数据对象添加到JSON对象中
- jQuery+php如何在数据对象中返回多个值
- $http put v create - 每个 (JavaScript) 中从 .success() 返回的数据对象有什
- 数据对象内的 D3 循环数组
- 在jQuery的.on()数据对象中访问$(this)
- AngularJS模态窗口数据/对象流
- 关于在 Vue.js 中设置数据对象属性的最佳实践
- 如何构建数据对象以在不知道多少时传递给 ajax
- 如何访问放置在谷歌地图上的geoJSON数据中的数据对象