[英]How to access a object value of another angular component
Unfortunately I can't pass data between components. 不幸的是,我无法在组件之间传递数据。 I took the bcqr-reader demo at https://embed.plnkr.co/m9dtF9llcAw7eYE94b5k/preview and pass the scanned information to my second component. 我在https://embed.plnkr.co/m9dtF9llcAw7eYE94b5k/preview上进行了bcqr阅读器演示,并将扫描的信息传递给第二个组件。 First you can see my scan-component. 首先,您可以看到我的扫描组件。 "$scope.url" is my object of interest. “ $ scope.url”是我感兴趣的对象。
angular.module('foo').component('scan', {
bindings:{url:"="},
templateUrl: 'templates/scan.html',
controller:function($scope){
$scope.start = function() {
$scope.cameraRequested = true;
}
$scope.processURLfromQR = function (url) {
$scope.url = url;
$scope.cameraRequested = false;
}
}
});
My second component "show" is the destination of "$scope.url". 我的第二个组件“显示”是“ $ scope.url”的目标。 Later i will need $scope.url to use it as an id for a couchdb query. 稍后,我将需要$ scope.url来将其用作用于ouchdb查询的ID。 I read a lot, about data exchange between components but i didn't get i running. 我读了很多关于组件之间的数据交换的书,但是我没有让我运行。 I also tried to store the object as $rootScope. 我也尝试将对象存储为$ rootScope。 I would preferre an event based solution like $onChanges, but now every help is welcome. 我希望使用基于事件的解决方案,例如$ onChanges,但现在欢迎所有帮助。
angular.module('foo').component('show', {
template: '<p> Transfered value: {{$ctrl.url}}</p>',
bindings:{url:"="},
require: { url:'^scan'
},
controller: function () {
this.$onInit = function () {
console.log(this.foo.url); //
}; }
}); });
My app.js file looks like: 我的app.js文件如下所示:
myApp.config(function($stateProvider,$urlRouterProvider) {
var scanState = {
name: 'scan',
url: '/scan',
component:'scan'
}
var showState = {
name:'show',
url: '/show',
component:'show'
}
$stateProvider.state(scanState);
$stateProvider.state(showState);
$urlRouterProvider.otherwise("scan");
});
To share stuff between components you may resolve using Services. 要在组件之间共享内容,您可以使用服务来解决。 Services are singleton classes and what you store in them is available throughout your whole application. 服务是单例类,您在其中存储的内容在整个应用程序中都可用。 The thing to keep in mind with singleton classes is that the data stored is not persistent and will be cleared once the app is terminated. 单例类要记住的一点是,存储的数据不是持久性的,一旦应用程序终止,该数据将被清除。
app.service('service-name', function(){
var myVar = undefined;
var service-name = {
setVar: function(_value){
myVar = _value;
},
getVar: function(){
return myVar;
}
};
return service-name;
});
To use the service from a controller just declare it in the controller's dependency and use like so : 要使用控制器中的服务,只需在控制器的依赖项中声明它,并按如下方式使用:
form controller A : 表单控制器A:
var myValue = something; var myValue =某物;
service-name.setVar(myValue); service-name.setVar(myValue);
from controller B: 从控制器B:
var myVar = service-name.getVar(); var myVar = service-name.getVar();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.