【问题标题】:Angular binding error角度绑定错误
【发布时间】:2016-05-26 13:10:55
【问题描述】:

我的 Angular 应用程序出现一个奇怪的错误。

我有一个控制器,我在其中声明了一些变量。如果我要在 html 中编写它们,它会按预期工作。但是,如果我尝试更改它们,例如在输入框中,则不会发生任何事情。

即使我尝试从按钮调用函数或什么都没有发生。 下面的代码是我的控制器的简化版本。

angular.module('myModule', [])
.controller('myCtrl', ['$rootScope', '$scope', 'SomeServices',
    function ($rootScope, $scope, someServices) {
        'use strict';
        $scope.myVar = "foobar";
        $scope.myFunction = function() {
           // it never gets here
        }

        $scope.$watch("myVar", function() {
           // it even never gets here
        });
    }]);

我的 HTML

<!-- change this and the watcher will not doing anything -->
<!-- the value will bee foobar, but after that nothing happens -->
<input type="text" ng-model="myVar" /> 
<button ng-click="myFunction()">click here and nothing will happen</button>

如果我在 codepen 中尝试过,它可以正常工作。 有没有人有过这样的行为?

【问题讨论】:

  • 正如我所写 - 错误是没有任何反应。它就像绑定不起作用。我会再弄清楚一点。等一下
  • 请显示您的html,请显示完整的html。
  • 好的。我已经编辑了条目。
  • 您在该函数中没有输入任何内容,请将其粘贴到 myfunction ( ) $scope.myVar = "foobar";或者你想要什么点击按钮??
  • 输入字段是否被预填?

标签: angularjs binding


【解决方案1】:

我看不出它为什么不工作的任何问题,可能这是更简化的演示,

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

app.controller('MainCtrl', function($scope) {
  $scope.myVar = "foobar";
  $scope.myFunction = function() {
    console.log($scope.myVar + ' myFunction called')
  }

  $scope.$watch("myVar", function() {
    console.log($scope.myVar + ' value changed')
  });
});
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9">
</script>
<div ng-app="myApp" ng-controller="MainCtrl">
  <input type="text" ng-model="myVar" />
  <button ng-click="myFunction()">click here and nothing will happen</button>
</div>

打开开发者工具查看日志。

如果您遇到其他问题,请详细说明。

【讨论】:

    猜你喜欢
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    相关资源
    最近更新 更多