在此代码中,我使用了两个动​​态变量fbidfburlfburl是使用fbid的表达式。

$scope.fburl = "https://graph.facebook.com/"+$scope.fbid+"/picture?type=normal";

这是我的代码。



// Code goes here
angular.module("testApp", [])
  .controller("testCtrl", function($scope) {
    $scope.fbid = "bennadel";
    $scope.fburl = "https://graph.facebook.com/"+$scope.fbid+"/picture?type=normal";
    console.log($scope.fburl);
  })

<!DOCTYPE html>
<html ng-app="testApp">

  <head>
    <script data-require="angular.js@*" data-semver="1.4.0-beta.4" src="https://code.angularjs.org/1.4.0-beta.4/angular.js"></script>
    <link href="style.css" rel="stylesheet" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="testCtrl">
    FacebookID<input type="text" ng-model="fbid" >
    <img ng-src= "{{fburl}}"/>
   <div>{{fburl}}</div>
  </body>

</html>





现在我的问题是,当我更新fbid时,为什么fburl没有自动更新?

最佳答案

这是因为事后该值无法更新,您需要在变量fbid上添加观察者。

AngularJS docuemntation for $watch



// Code goes here
angular.module("testApp", [])
  .controller("testCtrl", function($scope) {
    $scope.fbid = "bennadel";
    $scope.fburl = "";
    $scope.$watch('fbid ', function(newValue, oldValue) {
        $scope.fburl = "https://graph.facebook.com/"+newValue+"/picture?type=normal";
        console.log($scope.fburl);
    });
  })

<!DOCTYPE html>
<html ng-app="testApp">

  <head>
    <script data-require="angular.js@*" data-semver="1.4.0-beta.4" src="https://code.angularjs.org/1.4.0-beta.4/angular.js"></script>
    <link href="style.css" rel="stylesheet" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="testCtrl">
    FacebookID<input type="text" ng-model="fbid" >
    <img ng-src= "{{fburl}}"/>
   <div ng-bind="fburl"></div>
  </body>

</html>

10-02 17:30