【问题标题】:phonegap/ionic - $scope inside of click function not updatingphonegap/ionic - click 函数内的 $scope 未更新
【发布时间】:2014-06-04 01:16:23
【问题描述】:

我有一个简单的设置,我想单击一个按钮并从输入控件获取数据。问题是 click 函数内部的 $scope 变量保持与代码第一次运行时相同的值。当我在网络上创建小提琴时,一切都按计划进行。

HTML

<div ng-app>
    <div ng-controller="TodoCtrl">
        <input type="text" ng-model="authenticationCode">
        <br>
        <button class="button" ng-click="authenticate()">Authenticate</button>
        <br>
        <span>Auth info: {{authinfo}}</span>
        <br>
        <span>authenticationCode - {{authenticationCode}}</span>
    </div>
</div>

JavaScript

function TodoCtrl($scope) {
    $scope.authenticationCode = 'TESTER';
$scope.authenticate = function(){
        var t = $scope.authenticationCode;
    $scope.authinfo = t;
    };
}

Fiddle of the code working in web

当我在 PhoneGap 中运行它时

  • 在输入框中使用“TESTER”加载屏幕
  • 以“测试”作为“authenticationCode -”值的屏幕加载
  • 将输入中的“TESTER”更改为“CHANGED”会将“authenticationCode -”更新为“CHANGED”
  • 单击“验证”会将值“测试”作为“验证信息:”

我不知道为什么 $scope.authenticationCode 没有在 authentication 函数中更新它的值。我也不确定为什么这在网络中有效,而且我在使用 Ionic 的 PhoneGap 中遇到问题。

【问题讨论】:

标签: angularjs cordova ionic-framework


【解决方案1】:

这个问题可能是因为TodoCtrl中使用了原语,请试试这个 -

HTML

<div ng-controller="TodoCtrl">
    <label class="item item-input">
        <input type="text" ng-model="input.authenticationCode">
    </label>
    <br>
    <button class="button" ng-click="authenticate()">Authenticate</button>
    <br><br>
    <span>Auth info: {{input.authInfo}}</span>
    <br>
    <span>authenticationCode - {{input.authenticationCode}}</span>
</div>

JavaScript

.controller('TodoCtrl', ['$scope', function($scope) {
    $scope.input = {
        authenticationCode: 'TESTER',
        authInfo: ''
    };

    $scope.authenticate = function() {
        $scope.input.authInfo = $scope.input.authenticationCode;
        console.log('authInfo: ' + $scope.input.authInfo);
    };
}]);

Here is a CodePen of the above

【讨论】:

  • 感谢您的回复,但不幸的是他们都没有工作。使用 $watch,authinfo 在按下按钮时没有任何价值。使用 $timeout,我得到了与原始问题相同的结果。该值仍然是“测试者”。
  • @VtoCorleone 我更新了不使用原始值的答案,这可能是继承问题。您在console.log 中看到newValue$scope.$watch 中的什么?
  • @VtoCorleone 另外,请注意我将authinfo 更改为authInfo
  • console.log 不会在 $watch 函数中向 logcat 打印任何内容。
  • @VtoCorleone 您是否将标记更新为 &lt;input type="text" ng-model="input.authenticationCode"&gt; 而不是 &lt;input type="text" ng-model="authenticationCode"&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多