我是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
。我做错了什么提前谢谢。
答案 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>