将范围传递给函数不起作用

时间:2016-08-31 08:31:02

标签: javascript angularjs

我是angular.js的新用户,$scope无法在控制器内部的函数中工作....

  <div>{{logMsg}}</div>

  <script type="text/javascript">
      angular.module("app",[] ).controller("myController", function($scope){
          $scope.onConnect = function(status){
          $scope.logMsg = "connecting...";
          } 
          function onMessage(msg) {
            console.log('message');
            $scope.logMsg = "message...";
          }
      });


  </script>

显示connecting...,但不显示message...。但是我收到了控制台中的message。我做错了什么提前谢谢。

4 个答案:

答案 0 :(得分:2)

如果您想使用$scope,最好使用“数组”符号

注入它

angular.module("app",[] ).controller("myController", ['$scope', function($scope){

不确定您希望$ scope存在,该函数是否在控制器之外且$ scope未注入onMessage函数。

也许你的意思是onMessage在控制器中,或者通过$scope从控制器调用它?

答案 1 :(得分:2)

在这种情况下,

$ scope是out of scope

<script type="text/javascript">

    angular.module("app",[] )
      .controller("myController", function($scope){ <- scope of $scope is from here
          $scope.onConnect = function(status){
             $scope.logMsg = "connecting...";
          } 
      }); <- to here

      function onMessage(msg) {
          console.log('message');
          $scope.logMsg = "message..."; <- no $scope here
      }
 </script>

解决方案是以与OnConnect相同的方式写入onMessage。或者将$ scope分配给另一个不推荐的变量。

答案 2 :(得分:1)

$scope.logMsg中的onMessage不在您的控制器范围内。见下面的更正。

 angular.module("app", []).controller("myController", ['$scope',function($scope) {
   $scope.logMsg = "";
   $scope.onConnect = function(status) {
     $scope.logMsg = "connecting...";
   }
   $scope.onMessage = function(msg) {
     console.log('message');
     $scope.logMsg = "message...";
   };
 }]);

答案 3 :(得分:1)

您需要向onMessage函数注入$ scope以获取$ scope的引用。在这种情况下,$scope仅在控制器方法的范围内可用,而不在onMessage方法内。

angular.module("app",[] ).controller("myController", function($scope, $timeout){
          $scope.onConnect = function(status){
          $scope.logMsg = "connecting...";
          } 
          $scope.onConnect();
          $timeout(onMessage($scope), 2000);
      });

          function onMessage($scope) {
            return function(msg){
              console.log('message');
              $scope.logMsg = "message...";
            }            
          }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myController">{{logMsg}}</div>