console.log for $scope in angular js
为什么我不能控制台输出$scope值?我正在尝试从页面中提取用户分配的值并在控制器中检索。最后,我希望将此传递给服务,以便多个控制器可以访问这些数据。
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <!DOCTYPE html> <html lang="en-us" ng-app="myApp"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta charset="UTF-8"> <link rel="stylesheet" href="css/bootstrap.min.css" /> <!-- CDN lib files --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-animate.js"> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.1.0/ui-bootstrap-tpls.min.js"> <!-- custom angular script --> <script src="js/app.js"> </head> <body> Hello world! <label> Please enter something</label> <input textarea ng-model="name"></input> <h4> This is what you entered : {{ name }} </h4> <h4 style=color:red> now filtering: {{ lower() }}</h4> </body> </html> |
App.JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var myApp = angular.module('myApp', []); myApp.controller('mainController', ['$scope', '$filter', function($scope, $filter) { $scope.name = 'Test '; $scope.lower = function(){ return $filter('lowercase')($scope.name); } $scope.name = $scope.lower(); console.log($scope.name); console.log($scope.lower()); }]); |
控制台将在初始化时输出值,但不会在用户进行更改后输出。
您需要观察范围变量:
1 2 3 | $scope.$watch('name', function() { console.log($scope.name); }); |
更多信息:https://stackoverflow.com/a/15113029/5787736
只是一个更"实用"的版本。每个人都是对的,你记录的是可观察的,而不是观察到的。你想让
1 | $scope.$watch("name", console.log); |
您只从构造函数登录。如果您想在每次发生变化时记录日志,请考虑使用手表:
1 2 3 | $scope.$watch("name", function() { console.log($scope.name); } |
当作用域变量发生变化时,为什么您希望重新传递控制器?您可以使用范围监视程序或输入事件侦听器来侦听更改。
下面是一个观察者的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | var myApp = angular.module('myApp', []); myApp.controller('mainController', ['$scope', '$filter', function($scope, $filter) { $scope.name = 'Test '; $scope.lower = function(){ return $filter('lowercase')($scope.name); } $scope.name = $scope.lower(); console.log($scope.name); console.log($scope.lower()); $scope.$watch('name', function() { console.log($scope.name); console.log($scope.lower()); }); }]); |
1 2 3 4 5 6 7 8 | <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"> Hello world! <label>Please enter something</label> <input textarea ng-model="name" /> <h4> This is what you entered : {{ name }} </h4> <h4 style=color:red> now filtering: {{ lower() }}</h4> |