Angularjs 避免 $emit 并跨指令共享一个变量
Angularjs avoid $emit and share a variable across directives
我有一种情况,我想避免使用 $emit 共享一个范围变量,而是使用底层服务共享一些 属性,问题是 属性 值被设置在指令 1 中的承诺响应 return 以及通过指令 1 在服务中设置 属性 值时,指令 2 已经加载,因此 属性 在指令中未定义2.
有什么想法吗?
也许从指令 1 中提取将承诺交付给服务的功能,并在两个指令中使用
.then(function(data){ ... } )
根据提供的信息,想到了写这段代码。希望这会给您一些见解,以找到最佳答案。
angular.module('myApp').service('SomeService', function($http) {
this.readData = function(dataUrl) {
// read data;
return $http.get(dataUrl)
.then(function(res) {
return res.data;
}, function(res) {
return res;
}
}
return this;
});
angular.module('myApp').controller('MyController', function($scope, SomeService) {
$scope.readData = function(url) {
SomeService.readData(url)
.then(function(res) {
$scope.data = res;
}, function(res) {
// Display error
}
}
}
angular.module('myApp').directory('myDirectory1', function() {
return {
restrict: 'A',
link: function(scope, elm, attrs) {
scope.data = scope.readData(url);
}
}
});
angular.module('myApp').directory('myDirectory2', function() {
return {
restrict: 'A',
scope: {
data : '@'
},
link: function(scope, elm, attrs) {
scope.$watch('data', function(newVal) {
// Do some stuffs
});
}
}
});
我有一种情况,我想避免使用 $emit 共享一个范围变量,而是使用底层服务共享一些 属性,问题是 属性 值被设置在指令 1 中的承诺响应 return 以及通过指令 1 在服务中设置 属性 值时,指令 2 已经加载,因此 属性 在指令中未定义2. 有什么想法吗?
也许从指令 1 中提取将承诺交付给服务的功能,并在两个指令中使用
.then(function(data){ ... } )
根据提供的信息,想到了写这段代码。希望这会给您一些见解,以找到最佳答案。
angular.module('myApp').service('SomeService', function($http) {
this.readData = function(dataUrl) {
// read data;
return $http.get(dataUrl)
.then(function(res) {
return res.data;
}, function(res) {
return res;
}
}
return this;
});
angular.module('myApp').controller('MyController', function($scope, SomeService) {
$scope.readData = function(url) {
SomeService.readData(url)
.then(function(res) {
$scope.data = res;
}, function(res) {
// Display error
}
}
}
angular.module('myApp').directory('myDirectory1', function() {
return {
restrict: 'A',
link: function(scope, elm, attrs) {
scope.data = scope.readData(url);
}
}
});
angular.module('myApp').directory('myDirectory2', function() {
return {
restrict: 'A',
scope: {
data : '@'
},
link: function(scope, elm, attrs) {
scope.$watch('data', function(newVal) {
// Do some stuffs
});
}
}
});