al_kasih_empatix al_kasih_empatix - 27 days ago 15
AngularJS Question

Converting value dynamically from view to scope

I want to auto translate the language of every menu title from the view by a session that user have in his profile. The method that I need to use is by using our API Library that we have in our php framework.

In general usage of php, we will translate a word by using this command

$_lib->translate("wordToTranslate");


Then automatically it will translate the word of
wordToTranslate
into the language of the user have in his profile/session.

Now, since we are using IONIC and AngularJS, what I can do to achieve this is by calling a scope from template:

<p>{{translatethis("wordToTranslate")}}</p>


In controller I will have a scope of
translatethis


$scope.translatethis = function(arg) {

$http.post("http://example.com/API?Word=arg&Lang=1").success( function(response) {
console.log(response);
});
}


And I get this error

Error: 10 $digest() iterations reached.

It seems like the template never finish to get the real output of the
<p>{{translatethis("wordToTranslate")}}</p>


Can any body guide me how to clean this method, please, so that I avoid the error?

Many thanks in advance

Answer

Issue 1: Your translate request doesn't return a value so the interpolation ({{...}}) has nothing to interpolate!

Issue 2: Your translate request makes a $http request which returns a promise, not an actual value! This means you have nothing to interpolate.

My suggestion is to make a dictionary of the words and go from there.

As an example:

// Create some dictionaries
$scope.translatedWords = {};
$scope.requestedWords = {};

$scope.translatethis = function(arg) {
    if ($scope.translatedWords[arg]) {
        // We have already translated this word, return it
        return $scope.translatedWords[arg];
    } else {
        if (!$scope.requestedWords[arg]) {
            // We need to request the word
            // Setting this stops us from making multiple requests while the request gets resolved.
            $scope.requestedWords[arg] = true;
            requestTranslation(arg);
        }
        return '';
    }
}

// Has no need to be on $scope as it's a private function
function requestTranslation(arg) {
    $http.post("http://example.com/API?Word=arg&Lang=1").success( function(response) {
      console.log(response); 
      // Store the result of the translation into our map
      $scope.translatedWords[arg] = response.data;
    });
}
Comments