gpt4 book ai didi

javascript - 如何在 AngularJS 中的不同 Controller 中设置变量?

转载 作者:行者123 更新时间:2023-11-30 17:14:33 24 4
gpt4 key购买 nike

我想用 Angular 做简单的通知。这是我写的代码。 http://pastebin.com/zYZtntu8问题是:为什么如果我在 hasAlerts() 方法中添加一个新警报它会起作用,但如果我在 NoteController 中添加一个新警报它就不会。我用 $scope.$watch 尝试过一些东西,但它也不起作用,或者我做错了什么。

我该怎么做?

最佳答案

看看我不久前做的这个 plnkr

http://plnkr.co/edit/ABQsAxz1bNi34ehmPRsF?p=preview

我展示了 Controller 可以使用来自服务的数据的几种方式,特别是前两种展示了如何在没有 watch 的情况下进行操作,这通常是一种更有效的方式:

// Code goes here

angular.module("myApp", []).service("MyService", function($q) {
var serviceDef = {};
//It's important that you use an object or an array here a string or other
//primitive type can't be updated with angular.copy and changes to those
//primitives can't be watched.
serviceDef.someServiceData = {
label: 'aValue'
};
serviceDef.doSomething = function() {
var deferred = $q.defer();

angular.copy({
label: 'an updated value'
}, serviceDef.someServiceData);

deferred.resolve(serviceDef.someServiceData);
return deferred.promise;
}
return serviceDef;
}).controller("MyCtrl", function($scope, MyService) {
//Using a data object from the service that has it's properties updated async
$scope.sharedData = MyService.someServiceData;
}).controller("MyCtrl2", function($scope, MyService) {
//Same as above just has a function to modify the value as well
$scope.sharedData = MyService.someServiceData;
$scope.updateValue = function() {
MyService.doSomething();
}
}).controller("MyCtrl3", function($scope, MyService) {
//Shows using a watch to see if the service data has changed during a digest
//if so updates the local scope
$scope.$watch(function(){ return MyService.someServiceData }, function(newVal){
$scope.sharedData = newVal;
})
$scope.updateValue = function() {
MyService.doSomething();
}
}).controller("MyCtrl4", function($scope, MyService) {
//This option relies on the promise returned from the service to update the local
//scope, also since the properties of the object are being updated not the object
//itself this still stays "in sync" with the other controllers and service since
//really they are all referring to the same object.
MyService.doSomething().then(function(newVal) {
$scope.sharedData = newVal;
});
});

我想这里值得注意的是,我使用 angular.copy 重新使用在服务中创建的相同对象,而不是为该属性分配新对象或数组。因为它是同一个对象,如果您从 Controller 引用该对象并在任何数据绑定(bind)情况下使用它( watch 或 View 中的 {{}} 插值),将会看到对象的更改。

关于javascript - 如何在 AngularJS 中的不同 Controller 中设置变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26366796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com