如何在Angular中更新我的视图/范围

时间:2016-09-08 09:16:24

标签: javascript angularjs scope angularjs-scope

在范围内,“ug”属性依赖于“user”和“age”,当我更新“user”或“age”时为什么“ug”不更新?我怎样才能更新“ug”

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
    user:<input ng-model="user">
    <br>
    age:<input ng-model="age">
    <br>
    user and age : <span style="color: red" ng-bind="user + '-and-' + age"></span>
    <br>
    ug:<span style="color:red;" ng-bind="ug"></span>
    <br>
    addAge:<span style="color:red;" ng-bind="addAge"></span>
</div>

ANGULAR JS CODE

angular.module('myApp', [])
    .controller('ctrl', ['$scope', function($scope) {
        var fn = function(user, age) {
            //TODO
            return user + '-fn-' + age;
        }
        $scope.user = 'taven';
        $scope.age = '30';
        $scope.ug = fn($scope.user, $scope.age);
    }]);

2 个答案:

答案 0 :(得分:0)

Ins ng-bind="ug"ng-bind="fn(user, age)"。 当然,还要在控制器代码中添加:$scope.fn = fn;

<强> HTML:

ug:<span style="color:red;" ng-bind="fn(user, age)"></span>

<强>使用Javascript:

.controller('ctrl', ['$scope', function($scope){
    $scope.user = 'taven';
    $scope.age = '30';
    $scope.fn = function(user, age){
        //TODO
        return user + '-fn-' + age;
    }
}]);

答案 1 :(得分:0)

您可以调用ng-click事件来更新此范围。

&#13;
&#13;
angular.module('myApp', [])
            .controller('ctrl', ['$scope', function($scope){
                var fn = function(user, age){
                    //TODO
                    return user + '-fn-' + age;
                }
                $scope.user = 'taven';
                $scope.age = '30';
                $scope.updateScope = function(){
                  $scope.ug = fn($scope.user, $scope.age);
                }
                
            }]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
    user:<input ng-model="user">
    <br>
    age:<input ng-model="age">
    <br>
    user and age : <span style="color: red" ng-bind="user + '-and-' + age"></span>
    <br>
    ug:<span style="color:red;" ng-bind="ug"></span>
    <br>
    addAge:<span style="color:red;" ng-bind="addAge"></span>
  
    <button ng-click=updateScope()>Update scope</button
</div>
&#13;
&#13;
&#13;