javascript angularjs ng-click 无法更改 $scope 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22171953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:36:30  来源:igfitidea点击:

angularjs ng-click can't change $scope variable?

javascriptangularjs

提问by user1803975

I'm baffled here I've got a controller which looks like this..

我很困惑,我有一个看起来像这样的控制器..

angular.module('publicRegApp')
  .controller('CompanyNameController', function ($scope) {
    $scope.title = 'Title One';

    $scope.onSearch = function(){
        console.log("clicked");
        $scope.title = "Title Two";
    }

  });

in my template I have:

在我的模板中,我有:

<button type="submit" class="btn btn-default" ng-click="onSearch()">Search</button>

When I click the button the console log gets fired but the $scope.title doesn't change. I'm so confused please help :-(

当我单击按钮时,控制台日志被触发,但 $scope.title 不会改变。我很困惑请帮助:-(

回答by ustc-geeker

It works if you take care of these things:

如果你照顾好这些事情,它会起作用:

  1. Make sure you have ng-app="publicRegApp"somewhere
  2. Correct you Javascript from angular.module("publicRegApp")to angular.module("publicRegApp", [])which indicate that you don't depended on other angular module.
  3. Make sure {{title}}is in the controller scope
  1. 确保你有ng-app="publicRegApp"地方
  2. 纠正你的JavaScriptangular.module("publicRegApp")angular.module("publicRegApp", [])这表明,你不依赖于其他角模块。
  3. 确保{{title}}在控制器范围内

Here is working example: http://jsbin.com/xotaf/5/edit

这是工作示例:http: //jsbin.com/xotaf/5/edit

回答by maurycy

My guess is that your {{title}} in template is outside of scope for controller. I would strongly recommend to check it ;)

我的猜测是您在模板中的 {{title}} 超出了控制器的范围。我强烈建议检查它;)

$scope.$apply is very bad suggestion, it's not doing what you think it's doing

$scope.$apply 是一个非常糟糕的建议,它没有做你认为它在做的事情

------------EDIT---------

- - - - - - 编辑 - - - - -

check this plunker pls

请检查这个plunker

http://plnkr.co/edit/0LyUaGWK4J5c9EY74ndw?p=preview

http://plnkr.co/edit/0LyUaGWK4J5c9EY74ndw?p=preview

回答by user1803975

Not totally sure why but having

不完全确定为什么但有

<button type="submit">

was the issue. Changing to

是问题。更改为

<button type="button">

fixed it.

解决它。

I then realised I should probably be using ng-submit on the buttons's parent element which also fixed the problem (as long as I leave the button as submit of course)

然后我意识到我可能应该在按钮的父元素上使用 ng-submit 这也解决了这个问题(当然,只要我将按钮保留为提交)