$ scope.value仅在第二次点击后发生变化

时间:2016-03-14 20:59:47

标签: javascript angularjs angularjs-scope

有我的HTML代码:

<div ng-if="user.type == 'none'"> <button ng-click="selectUserType('user')"></button> </div>
<div ng-if="user.type !== 'none'"> //here goes input etc </div>

有我的剧本:

$scope.user = {type: 'none'};
$scope.selectUserType = function(type) {
 $location.path('/signup/'+type);
 $scope.user.type = type;
};

问题是,在第一次点击控制台后,我看到$ scope.user获得'用户'值,然后立即回到'无',但位置改变为我需要的。 $ scope.user在第二次单击后再次获得所需的值,并隐藏有用的块并显示所需的内容。

我怎么能以另一种方式做到这一点?我需要通过一次点击完成所有这些

当我删除$location.path('/signup/'+type)时它会起作用,但是当user.type被更改时我仍然需要更改我的location.path

对不起我的英语,如果你看到一些语法错误或其他什么。这不是我的原生,谢谢。

2 个答案:

答案 0 :(得分:0)

试试这段代码(这不是最好的方法):

var $user = {type: 'none'}; // define OUTSIDE of controller(or link function)

控制器内的代码(或链接功能)

$scope.user = $user;
$scope.selectUserType = function(type) {
    $location.path('/signup/' + type);
    $user.type = type;
    $scope.user = angular.extend({}, $user);
};

我猜你的控制器在你的情况下初始化两次,所以尝试在控制器之外定义$ user变量,例如在全局范围内(也可以尝试在$ rootScope中定义它),所以当控制器重新启动时它是不是chage $ user变量。

答案 1 :(得分:0)

在路上,Dmitriy Loskutov回答我,我用过这个: 只需检查控制器启动时的location.path,然后设置类型:

    var locPath = $location.path();
    if (locPath == '/signup') {
        $scope.user = {type: 'none'};
    } else if (locPath == '/signup/user') {
        $scope.user = {type: 'user'};
    }

    $scope.selectUserType = function(type) {
        $location.path('/signup/' + type);
        $scope.user.type = type;
    };

希望,这有助于某人,因为我已经失去了大约4个小时来获得这个简单的解决方案&gt; _&lt;

相关问题