Angular 具有动态范围或变量的服务
Angular Service with dynamic scope or var
我需要一个为我提供范围或动态变量的服务,所以我转向其他控制器。
我在 JSBin 上做了一个测试,但没有用。
https://jsbin.com/semozuceka/edit?html,js,console,output
angular.module('app', [])
.controller('control1', function($scope, shared) {
shared.set('teste', {
testecontroller1: "Apenas um teste"
});
$scope.teste = shared.get();
$scope.teste2 = shared.get();
})
.controller('control2', function($scope, shared) {
$scope.teste = shared.get('teste');
shared.set('teste2', {
testecontroller2: "Apenas um teste"
});
$scope.teste2 = shared.get('teste2');
})
.service('shared', function($scope) {
$scope.data = {};
this.set = function(key, obj) {
$scope.data[key] = obj;
};
this.get = function(key) {
return $scope.data[key];
};
});
不要尝试使用 $scope
,因为它会尝试使用 scopeProvider
。您不能将其注入服务。此外,服务的输入是一个数组(其中包含一个函数),而不仅仅是一个函数。
话虽如此,如果您在服务中跟踪变量,则根本不需要作用域。
.service('shared', [function() {
var data = {};
return {
set: function(v, val) {
data[v] = val;
},
get: function(v) {
return (v)? data[v]: data;
}
};
}]);
我会选择工厂服务,因为不需要创建自定义服务。鉴于您的控制器的功能,我创建了一个简单的工厂,如下所示:
.factory('shared', function() {
var shared;
var data = {};
shared = {
set: setFunc,
get: getFunc
};
return shared;
function setFunc(key, input){
data[key] = input;
}
function getFunc(key){
if(key)
return data[key];
else return data;
}
})
唯一可能需要澄清的部分是 getFunc
。在 control1
中,您想在不指定任何属性的情况下获取 data
对象。但是,在 control2
中你确实指定了,这导致了条件 if(key)
。所以综上所述,这个函数检查是否有传递的属性参数和returns适当的数据。
这是一个有效的 plunker。
您可以在官方 documentation.
中阅读更多关于不同 Angular 提供商的信息以及它们之间的比较
尽情享受吧!
我需要一个为我提供范围或动态变量的服务,所以我转向其他控制器。
我在 JSBin 上做了一个测试,但没有用。
https://jsbin.com/semozuceka/edit?html,js,console,output
angular.module('app', [])
.controller('control1', function($scope, shared) {
shared.set('teste', {
testecontroller1: "Apenas um teste"
});
$scope.teste = shared.get();
$scope.teste2 = shared.get();
})
.controller('control2', function($scope, shared) {
$scope.teste = shared.get('teste');
shared.set('teste2', {
testecontroller2: "Apenas um teste"
});
$scope.teste2 = shared.get('teste2');
})
.service('shared', function($scope) {
$scope.data = {};
this.set = function(key, obj) {
$scope.data[key] = obj;
};
this.get = function(key) {
return $scope.data[key];
};
});
不要尝试使用 $scope
,因为它会尝试使用 scopeProvider
。您不能将其注入服务。此外,服务的输入是一个数组(其中包含一个函数),而不仅仅是一个函数。
话虽如此,如果您在服务中跟踪变量,则根本不需要作用域。
.service('shared', [function() {
var data = {};
return {
set: function(v, val) {
data[v] = val;
},
get: function(v) {
return (v)? data[v]: data;
}
};
}]);
我会选择工厂服务,因为不需要创建自定义服务。鉴于您的控制器的功能,我创建了一个简单的工厂,如下所示:
.factory('shared', function() {
var shared;
var data = {};
shared = {
set: setFunc,
get: getFunc
};
return shared;
function setFunc(key, input){
data[key] = input;
}
function getFunc(key){
if(key)
return data[key];
else return data;
}
})
唯一可能需要澄清的部分是 getFunc
。在 control1
中,您想在不指定任何属性的情况下获取 data
对象。但是,在 control2
中你确实指定了,这导致了条件 if(key)
。所以综上所述,这个函数检查是否有传递的属性参数和returns适当的数据。
这是一个有效的 plunker。
您可以在官方 documentation.
中阅读更多关于不同 Angular 提供商的信息以及它们之间的比较尽情享受吧!