如何在AngularJS中的不同控制器中设置变量?

时间:2014-10-14 17:33:40

标签: javascript angularjs angularjs-scope controllers

我想以角度进行简单的通知。这是我写的代码。 http://pastebin.com/zYZtntu8 问题是: 为什么我在hasAlerts()方法中添加一个新的警报它可以工作,但如果我在NoteController中添加一个新的警报它不会。我已尝试使用$ scope。$ watch但它也不起作用或我做错了。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

看看这个plnkr我做了一会儿

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

我展示了控制器可以使用服务数据的几种方式,特别是前两个显示如何在没有手表的情况下进行操作,这通常是一种更有效的方式:

// 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来重用在服务中创建的相同对象,而不是将新对象或数组分配给该属性。如果您从控制器引用该对象并在任何数据绑定情况下使用它(在视图中监视或{{}}插值),它将是相同的对象,因为它将看到对象的更改。