如何在ng-click函数中更改$ rootScope值?

时间:2016-04-21 07:56:01

标签: javascript angularjs

我试图通过另一个控制器中的另一个函数更改我在控制器中设置的$rootScope.name的值,但是当我访问另一个控制器中的$rootScope.name时,该值保持不变组。例如:

app.controller('homectrl', function($scope, $rootScope){

$rootScope.name = "joshua";

})

app.controller('aboutctrl', function($scope, $rootScope){

$scope.send = function(newname)
{
$rootScope.name = newname;
}

})

app.controller('servicectrl', function($scope, $rootScope){

console.log($rootScope.name); // this outputs joshua instead of new name set in send function in about controller

})

2 个答案:

答案 0 :(得分:0)

您无法快速按下触发send()方法的按钮,以使servicectrl输出新名称。如果您真的想在按下按钮后看到$rootScope.name中的内容,您应该观察值或者观察它,例如。通过像这样更改servicectrl

$rootScope.$watch('name', function(newname) {
    console.log($rootScope.name);
});

答案 1 :(得分:0)

在这样的情况下,我会避免使用$rootScope,而是使用工厂服务,在两个控制器之间共享。

这是一个有效的例子:

var app = angular.module('myApp',[]);

app.controller('homectrl', function($scope, NameService){

  $scope.name = NameService.name;
  
  $scope.$watch(function(){return NameService.name}, function(newValue, oldValue){
    $scope.name = newValue;
});
  
});

app.controller('aboutctrl', function($scope, NameService){

  $scope.name = NameService.name;
  
  $scope.send = function(newname){
    NameService.changeName($scope.name);
    console.log('New name!', $scope.name);
  }

});

app.factory('NameService', function(){

  return {
    name : 'joshua',
    changeName : function(newName){
      this.name = newName;
    }
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">

  <div ng-controller="homectrl">
    <h3>Home Controller </h3>
    <p>{{name}}</p>
  </div>
  
  <hr>
  
  <div ng-controller="aboutctrl">
    <h3>About Controller </h3>
    <input type="text" ng-model="name" />
    <button ng-click="send($scope.name)">Change</button>
  </div>


</div>