user3427540
user3427540

Reputation: 1172

Why Expressions are not dynamically updated in angular controller?

Here in this code i have used two dynamic variables fbid and fburl. fburl is a expression using fbid.

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

Here is my code.

// 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>

Now my question is when I am updating the fbid why fburl is not updating automatically ?

Upvotes: 1

Views: 116

Answers (2)

Zeeshan Hassan Memon
Zeeshan Hassan Memon

Reputation: 8325

Alternate solution - cleaner way.

// Code goes here
angular.module("testApp", [])
  .controller("testCtrl", function($scope) {
    $scope.fbid = "bennadel";
$scope.fbFn = function() {
                return "https://graph.facebook.com/"+$scope.fbid+"/picture?type=normal";
            };
  })
<!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= "{{fbFn()}}"/>
    <div >{{fbFn()}}</div>
  </body>

</html>

Happy Helping!

Upvotes: 2

beije
beije

Reputation: 861

It's because the value can't update after the fact, you need to add a watcher on the variable 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>

Upvotes: 2

Related Questions