I want to get and change the variables in the top-level controller in the factory. Is it possible?
習慣沉默2017-05-15 17:08:12
Generally when I am working on a project, services serve two purposes:
First, they are used as public methods, such as submission methods, certain services in pop-up boxes, and other similar general services.
Second, it is used when transferring parameters or objects between certain controllers according to special needs. This situation is rare and is generally not recommended~
When you talk about changing the variables of the top-level controller in the service, I feel that you provided a fragment of your idea, rather than the fundamental demand point~ What is your demand?
某草草2017-05-15 17:08:12
It cannot be operated directly, there are two ways:
1. Change the value through the callback function
2. Change the value by passing the object parameters (array, object)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="myApp" >
<p ng-controller="myCtrl">
{{ value.name }} {{ value.value }}
</p>
<hr />
<p ng-controller="myCtrl2">
{{ value.name }} {{ value.value }}
</p>
<script>
var app = angular.module('myApp', []);
app.service('myService', function() {
this.valueSet = function(value){
this.valueFunction(value);
};
this.valueCallback = function(callback){
var newValue = {
name : "hello",
value : "world"
};
this.valueFunction(newValue);
callback(newValue);
};
this.valueFunction = function(value){
value.name += ",";
value.value += "!";
return value;
};
});
app.controller('myCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.value = {
name : "你好",
value : "世界"
};
//回调方式改版 $scope 的值
myService.valueCallback(function(value){
$scope.value = value;
});
}]);
app.controller('myCtrl2', ['$scope', 'myService', function($scope, myService) {
$scope.value = {
name : "你好",
value : "世界"
};
myService.valueSet($scope.value);
}]);
</script>
</body>
</html>
漂亮男人2017-05-15 17:08:12
Yes, it is possible, but it is not recommended.
Encapsulate the controller data into an object, and then pass it as a parameter to the factory method.