学习AngularJs:ng-model没有绑定到View

时间:2014-04-03 08:33:43

标签: asp.net angularjs

我对angularJS很新,你可以说这是我使用angularJS的第一天。

看起来很愚蠢我试图做一些基本的东西,但不管怎么说。

我有一个文本框,如果您输入1234,Count应该是555,或者如果您输入任何数字,那么550我应该1234在页面加载时,它显示我555但是当我在文本框中更改值时,Count没有变化。

<div ng-app>
        <div ng-controller="prCtrl">
            Enter Product ID to get the reviews details
            <input type="number" ng-model="productId" required />
            <br />
            Total Review Count = {{ Count }}
        </div>
</div>

function prCtrl($scope,$http) {
    $scope.productId = 1234;
    if ($scope.productId === 1234) {
        $scope.Count = 555;
    } else {
        $scope.Count = 550;
    }
}

如何根据文本框中输入的值更改{{ Count }}

感谢

2 个答案:

答案 0 :(得分:1)

选项是订阅模型更改并在那里执行您的逻辑:

控制器:

function prCtrl($scope,$http) {
    $scope.productId = 1234;
    $scope.$watch('productId', function(newValue, oldValue){
    if (newValue === 1234) {
            $scope.Count = 555;
        } else {
            $scope.Count = 550;
        }
    });
}

查看:

<div ng-app>
    <div ng-controller="prCtrl">
        Enter Product ID to get the reviews details
        <input type="number" ng-model="productId" required />
        <br />
        Total Review Count = {{ Count }}
    </div>
</div>

我已经测试过了,它看起来像你想做的那样。

最后一点 - 你提到你是棱角分明的新人 - 我强烈推荐在AngularJS上使用egghead.io的会话(https://egghead.io/lessons)。他们善于帮助您加速AngularJS:)

答案 1 :(得分:1)

或者,您可以使用功能,而无需使用 $ watch

观看值
function prCtrl($scope,$http) {
    $scope.productId = 1234;

    $scope.getCount = function() {
       if ($scope.productId === 1234) {
          return 555;
       } else {
          return 550;
       }
    }               

}

观点:

<div ng-app>
    <div ng-controller="prCtrl">
        Enter Product ID to get the reviews details
        <input type="number" ng-model="productId" required />
        <br />
        Total Review Count = {{ getCount() }} // replaced with function call
    </div>
</div>

当在范围内更改模型时,将调用此函数,因此它将始终更新您的值