angular.js - angular中factory里可以操作controller里的数据吗
PHP中文网
PHP中文网 2017-05-15 17:06:12
0
3
560

我想在factory中获取并改变顶级控制器里的变量 可以办到吗

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
習慣沉默

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?

某草草

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>
漂亮男人

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!