Friday, 19 September 2014

update Angularjs from JS

angularjs is my main language but sometime i have to use js or ajax to do some query from backend and still update display by angularjs binding.

the problem is when js or ajax fetch data back, I cannot update this data back to angularjs and the webpage cannot display the new values. 

There are two situations:

situation 1: 

1, i still in the angularjs file, I can print out the scope in the call back function.
2, but if i change the value in callback function, the value is changed, but the webpage still displays the old value.
3, it seems that the binding mechanism does not work.

my solution is call $apply function, like this:
$scope.currentUser {fname : "ffffffff00000"};
.... put your code here, you will have no problem with binding issue.

this is the code i use:

yam.getLoginStatus(function(response) {
   //--- this is the callback function. 
      $scope.currentUser = {fname : "ffffffff00000"};

this is a yammer api, which basically is a JS api.

situation 2:

if change or access angularjs's variables in another js files. you cannot access them directly, you should:

var xxxddd = angular.element('[ng-controller= xxxController]').scope().currentUser;

console.log("logged-------------------------- " + xxxddd);

xxxController is the controller name.

in your angularjs file you should have this :

angular.module('myapp', ['ui.bootstrap']).controller('xxxController', ['$scope',

and your html should looks like this:

<html xmlns="" lang="en-GB" xml:lang="en-GB"

<body class="body" ng-controller="xxxController">

No comments:

Post a comment