我在控制器中定义了一个变量$ scope.name,它将以
的形式传递给工厂MyService。$scope.name = MyService.name;
工厂里面有
var myserivce = {};
myservice.open = function() {
myservice.name = 'abc';
};
return myservice;
我想返回myservice.name,以便abc存储在$ scope.name中
我该怎么做?不使用rootScope
答案 0 :(得分:0)
在JavaScript中,通过将变量分配给对象的属性并传递对该对象的引用来共享变量。
app.factory("share", function() {
var objectRef = {};
return {
set: set,
get: get,
getRef: getRef,
};
function set(prop, val) {
objectRef[prop] = val;
}
function get(prop) {
return objectRef[prop];
}
function getRef() {
return objectRef;
}
});
share.get(prop)
方法在调用函数时返回属性的值。任何更改都不会更新以前返回的值。
share.getRef()
方法返回对该对象的引用。当对象的内容发生更改时,每个引用该对象的实体都将共享这些更改。
答案 1 :(得分:0)
如果我正确理解了您的问题,那么您想要的是Controller知道Service中的名称变量已更改,并且应该基于此更新视图。
这可以通过以下三种方式之一进行:
angular
.module("myApp", [])
.controller("CtrlList", CtrlList)
.service("MyService", MyService);
CtrlList.$inject = ["$scope", "MyService"];
MyService.$inject = ["$q", "$timeout"];
function CtrlList($scope, MyService) {
MyService.name.subscribe(function(name) {
$scope.name = name;
});
$scope.$watch(
function() {
return MyService.age;
},
function(newValue, oldValue) {
$scope.age = MyService.age;
console.log(newValue + " " + oldValue);
console.log(MyService.age);
}
);
MyService.open();
}
function MyService($q, $timeout) {
var myservice = { name: new rxjs.Subject(), age: 1 };
myservice.open = function() {
$timeout(function() {
myservice.name.next("Value Changed.");
myservice.age = 2;
}, 10000);
myservice.name.next("Initial Value.");
};
return myservice;
}
* {
font-family: "Work Sans";
padding: 0;
margin: 0;
}
body {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background: #F6F7EB;
}
.wrapper {
width: 500px;
border: 1px dotted gray;
padding: 10px;
}
.wrapper .heading {
font-size: 30px;
margin-bottom: 12px;
}
.wrapper p {
margin-bottom: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.3.3/rxjs.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Work+Sans:400' rel='stylesheet' type='text/css'>
<section class="wrapper">
<p class="heading">AngularJS v1.7.5 - Wait for 10 seconds to see changes</p>
<div ng-app="myApp">
<div class="container" ng-controller="CtrlList">
<p>This value is changed through rxjs : {{ name }}</p>
<p>This value is changed through watcher: {{ age }}</p>
</div>
</div>
</section>
答案 2 :(得分:0)
将共享数据保存在工厂或服务中:
app.factory('Holder', function() {
return {
name : 'abc'
};
});
app.controller('YourCtrl', function($scope, Holder) {
$scope.Holder = Holder;
var name = $scope.Holder.name;
});
可能会对您有所帮助。