由于$ http调用,ng-model未更新

时间:2017-03-11 02:26:47

标签: javascript angularjs

我尝试更新ng-model值作为$ http.get调用的结果,但它没有更新。

这是我的代码。

main.js

angular.module('app', [])
  .controller('mainCtrl', ['$http', function($http) {
    var main = this;
    main.show = true;

    $http({
      method: 'GET',
      url: 'api url'    
    })
    .then(function(res) {
      main.show = true; 
      console.log('succeed call, main.show: ' + main.show);        
    }, function(res) {
      main.show = false;
      console.log('failed call, main.show: ' + main.show);
    });

    console.log('out of call, main.show: ' + main.show);
  }]);

的index.html

...
<body ng-app='app' ng-controller='mainCtrl as main'>
  <a ng-show='main.show' href='/'>Succeed</a>
  <a ng-hide='main.show' href='/'>Failed</a>
</body>
...
api成功时

控制台日志

out of call, main.show: true
succeed call, main.show: true
api失败时

控制台日志

out of call, main.show: true
failed call, main.show: false

我的问题是html总是告诉我&#39; Succeed&#39;链接。

我尝试过很多东西,甚至使用$timeout$apply,但它也无效。

对于类似的问题有一些答案,但它对我不起作用。

我该怎么做才能解决问题?

4 个答案:

答案 0 :(得分:1)

您拨打http电话的方式是错误的。

首先在控制器中:

.controller('mainCtrl', ['$http', function($http) ...

在控制器中,第一个http应该作为字符串传递:'$http'

异步调用按以下方式进行:

var promise = $http({
            method : 'POST',
            url : baseUrl,
            headers : {
                'Content-Type' : 'application/x-www-form-urlencoded'
            },
            data : data
});

promise.then(function (response) {
        yourData = response.data;
        console.log(response.data);

        return yourData;
    })
    .catch(function (error) {
        console.log("Something went terribly wrong.");
    });

答案 1 :(得分:1)

一切都很好。

尝试以下示例。我故意指出错误的URL,因此服务调用将失败,最终将进入失败回调。

演示

angular.module('app', [])
  .controller('mainCtrl', ['$http', function($http) {
    var main = this;
    main.show = true;

    $http({
        method: 'GET',
        url: 'http://jsonplaceholder.typicode.com/photos1'
      })
      .then(function(success) {
        main.show = true;
        console.log('succeed call, main.show: ' + main.show);
      }, function(error) {
        main.show = false;
        console.log('failed call, main.show: ' + main.show);
      });

    console.log('out of call, main.show: ' + main.show);
  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>

<body ng-app='app' ng-controller='mainCtrl as main'>
  <a ng-show='main.show' href='/'>Succeed</a>
  <a ng-hide='main.show' href='/'>Failed</a>
</body>

答案 2 :(得分:0)

将main.show初始值设置为false  

main.show =false;

还在HTML标记中定义ng-app值

答案 3 :(得分:0)

在上面的代码中,console.log(&#39;没有通话,main.show:&#39; + main.show);在http请求执行之前得到打印,这就是你总是收到main.show = true的原因。 如果你想访问main.show,那么在http请求成功或失败后你应该总是这样做。

<center><canvas id = "gameCanvas" width = "500" height = "500" style = "border:1px solid navy;"></canvas></center>
var canvas, ctx;
var clip = {};
var arsenal = {};
var enemyClip = {};
var keyDown = {};
var enemy = {};
window.onload = function() {
    canvas = document.getElementById("gameCanvas");
    ctx = canvas.getContext("2d");
    for (var i = 0; i < 3; i++) {
        createEnemy(Math.random(), i * 100 + 140);
    }
    setInterval(function() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        update();
    }, 1000 / 30);
}
var player = {
    x: 240,
    y: 240,
    w: 20,
    h: 20,
    color: "navy",
    alive: true,
    canShoot: true,
    canNuke: true,
    facingRight: true,
    draw: function() {
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x, this.y, this.w, this.h);
    },
    shoot: function() {
        if (player.canShoot) {
            player.canShoot = false;
            if (player.facingRight) {
                createPlayerBullet(Math.random(), player.x + player.w, player.y + player.h / 2, true);
            } else {
                createPlayerBullet(Math.random(), player.x, player.y + player.h / 2, false);
            }
            setTimeout(function() {
                player.canShoot = true;
            }, 750);
        }
    },
    nuke: function() {
        if (player.canNuke) {
            player.canNuke = false;
            createNuke(Math.random(), player.x + player.w / 2, player.y + player.h);
            setTimeout(function() {
                player.canNuke = true;
            }, 2000);
        }
    }
}
//var enemy = {
//  x:240,
//  y:480,
//  w:20,
//  h:20,
//  color:"maroon",
//  alive:true,
//  canShoot:true,
//  
//  draw:function(){
//      ctx.fillStyle = this.color;
//      ctx.fillRect(this.x, this.y, this.w, this.h);
//  },
//  
//  shoot:function(){
//      if(enemy.canShoot){
//          enemy.canShoot = false;
//      
//          if(player.x >= enemy.x && player.y <= enemy.y){// Top Right: TF, Bottom Right: TT, Bottom Left: FT, Top Left: FF
//              createEnemyBullet(Math.random(), enemy.x + enemy.w/2, enemy.y, player.x, player.y, true, false); // True equals ___ is greater than
//          }else if(player.x >= enemy.x && player.y >= enemy.y){
//              createEnemyBullet(Math.random(), enemy.x + enemy.w/2, enemy.y, player.x, player.y, true, true);
//          }else if(player.x <= enemy.x && player.y >= enemy.y){
//              createEnemyBullet(Math.random(), enemy.x + enemy.w/2, enemy.y, player.x, player.y, false, true);
//          }else if(player.x <= enemy.x && player.y <= enemy.y){
//              createEnemyBullet(Math.random(), enemy.x + enemy.w/2, enemy.y, player.x, player.y, false, false);
//          }
//          
//          setTimeout(function(){
//              enemy.canShoot = true;
//          }, 750);
//      }
//  }
//}
var createEnemy = function(ID, X) {
    var e = {
        x: X,
        y: 480,
        w: 20,
        h: 20,
        color: "maroon",
        alive: true,
        canShoot: true,
        id: ID,
        draw: function() {
            ctx.fillStyle = this.color;
            ctx.fillRect(this.x, this.y, this.w, this.h);
        },
        shoot: function() {
            if (this.canShoot) {
                this.canShoot = false;
                if (player.x >= this.x && player.y <= this.y) { // Top Right: TF, Bottom Right: TT, Bottom Left: FT, Top Left: FF
                    createEnemyBullet(Math.random(), this.x + this.w / 2, this.y, player.x, player.y, true, false); // True means greater than
                } else if (player.x >= this.x && player.y >= this.y) {
                    createEnemyBullet(Math.random(), this.x + this.w / 2, this.y, player.x, player.y, true, true);
                } else if (player.x <= this.x && player.y >= this.y) {
                    createEnemyBullet(Math.random(), this.x + this.w / 2, this.y, player.x, player.y, false, true);
                } else if (player.x <= this.x && player.y <= this.y) {
                    createEnemyBullet(Math.random(), this.x + this.w / 2, this.y, player.x, player.y, false, false);
                }
                setTimeout(function() {
                    enemy.canShoot = true;
                }, 750);
            }
        }
    };
    enemy[e.id] = e;
}
var createPlayerBullet = function(ID, X, Y, dir) {
    var playerBullet = {
        x: X,
        y: Y,
        w: 5,
        h: 5,
        color: "navy",
        id: ID,
        facingRight: dir,
        draw: function() {
            ctx.fillStyle = this.color;
            ctx.fillRect(this.x, this.y, this.w, this.h);
        }
    }
    clip[playerBullet.id] = playerBullet;
}
var createEnemyBullet = function(ID, X, Y, playerx, playery, dirx, diry) {
    var enemyBullet = {
        x: X,
        y: Y,
        w: 5,
        h: 5,
        color: "maroon",
        id: ID,
        dirX: dirx,
        dirY: diry,
        playerX: playerx,
        playerY: playery,
        draw: function() {
            ctx.fillStyle = this.color;
            ctx.fillRect(this.x, this.y, this.w, this.h);
        }
    }
    enemyClip[enemyBullet.id] = enemyBullet;
}
var createNuke = function(ID, X, Y) {
    var nuke = {
        x: X,
        y: Y,
        w: 5,
        h: 5,
        color: "green",
        id: ID,
        draw: function() {
            ctx.fillStyle = this.color;
            ctx.fillRect(this.x, this.y, this.w, this.h);
        }
    }
    arsenal[nuke.id] = nuke;
}
var updateEntity = function() {
    for (var playerBullet in clip) {
        clip[playerBullet].draw();
        if (clip[playerBullet].facingRight) {
            clip[playerBullet].x += 8;
        } else {
            clip[playerBullet].x -= 8;
        }
        if (clip[playerBullet].x <= 0) {
            delete clip[playerBullet];
        } else if (clip[playerBullet].x >= canvas.width) {
            delete clip[playerBullet];
        }
    }
    for (var nuke in arsenal) {
        arsenal[nuke].draw();
        arsenal[nuke].y += 3;
        if (arsenal[nuke].y >= canvas.height) {
            delete arsenal[nuke];
        }
    }
    for (var enemyBullet in enemyClip) {
        for (var e in enemy) {
            var dx = enemy[e].x - enemyClip[enemyBullet].playerX;
            var dy = enemy[e].y - enemyClip[enemyBullet].playerY;
            var angle = Math.atan2(dy, dx);
        }
        enemyClip[enemyBullet].draw();
        if (enemyClip[enemyBullet].dirX && !enemyClip[enemyBullet].dirY) {
            enemyClip[enemyBullet].x -= 10 * Math.cos(angle);
            enemyClip[enemyBullet].y -= 10 * Math.sin(angle);
        } else if (enemyClip[enemyBullet].dirX && enemyClip[enemyBullet].dirY) {
            enemyClip[enemyBullet].x -= 10 * Math.cos(angle);
            enemyClip[enemyBullet].y -= 10 * Math.sin(angle);
        } else if (!enemyClip[enemyBullet].dirX && enemyClip[enemyBullet].dirY) {
            enemyClip[enemyBullet].x -= 10 * Math.cos(angle);
            enemyClip[enemyBullet].y -= 10 * Math.sin(angle);
        } else if (!enemyClip[enemyBullet].dirX && !enemyClip[enemyBullet].dirY) {
            enemyClip[enemyBullet].x -= 10 * Math.cos(angle);
            enemyClip[enemyBullet].y -= 10 * Math.sin(angle);
        }
        if (enemyClip[enemyBullet].x <= 0) {
            delete enemyClip[enemyBullet];
        } else if (enemyClip[enemyBullet].x >= canvas.width) {
            delete enemyClip[enemyBullet];
        } else if (enemyClip[enemyBullet].y <= 0) {
            delete enemyClip[enemyBullet];
        } else if (enemyClip[enemyBullet].y >= canvas.height) {
            delete enemyClip[enemyBullet];
        } else if (enemyClip[enemyBullet].x >= player.x && enemyClip[enemyBullet].x <= player.x + player.w && enemyClip[enemyBullet].y >= player.y && enemyClip[enemyBullet].y <= player.y + player.h) {
            delete enemyClip[enemyBullet];
        }
    }
}
var update = function() {
    updateEntity();
    if (player.alive) {
        player.draw();
    }
    //if(enemy.alive){
    //  enemy.draw();
    //  enemy.shoot();
    //}
    for (var e in enemy) {
        ctx.fillStyle = enemy[e].color;
        ctx.fillRect(enemy[e].x, enemy[e].y, enemy[e].w, enemy[e].h);
        if (enemy[e].canShoot) {
            enemy[e].canShoot = false;
            if (player.x >= enemy[e].x && player.y <= enemy[e].y) { // Top Right: TF, Bottom Right: TT, Bottom Left: FT, Top Left: FF
                createEnemyBullet(Math.random(), enemy[e].x + enemy[e].w / 2, enemy[e].y, player.x, player.y, true, false); // True equals ___ is greater than
            } else if (player.x >= enemy[e].x && player.y >= enemy[e].y) {
                createEnemyBullet(Math.random(), enemy[e].x + enemy[e].w / 2, enemy[e].y, player.x, player.y, true, true);
            } else if (player.x <= enemy[e].x && player.y >= enemy[e].y) {
                createEnemyBullet(Math.random(), enemy[e].x + enemy[e].w / 2, enemy[e].y, player.x, player.y, false, true);
            } else if (player.x <= enemy[e].x && player.y <= enemy[e].y) {
                createEnemyBullet(Math.random(), enemy[e].x + enemy[e].w / 2, enemy[e].y, player.x, player.y, false, false);
            }
            setTimeout(function() {
                for (var e in enemy) {
                    enemy[e].canShoot = true;
                }
            }, 750);
        }
    }
    if (37 in keyDown) {
        player.facingRight = false;
        player.x -= 5;
    }
    if (38 in keyDown) {
        player.y -= 5;
    }
    if (39 in keyDown) {
        player.facingRight = true;
        player.x += 5;
    }
    if (40 in keyDown) {
        player.y += 5;
    }
    if (32 in keyDown) {
        player.shoot();
    }
    if (90 in keyDown) {
        player.nuke();
    }
}
addEventListener("keydown", function(e) {
    keyDown[e.keyCode] = true;
});
addEventListener("keyup", function(e) {
    delete keyDown[e.keyCode];
});