简体   繁体   中英

best practice to set controller scope variable from factory function?

I have working code below to set controller 'HelloCtrl' scope variable 'root' from factory 'testFactory' function setRoot(). I'm using ng-submit="testSubmit()" with ng-model="test" in my HTML. I'm afraid it's not the best practice, what else would you recommend ?

angular.module('testApp', [])
.controller('HelloCtrl', function ($scope, testFactory, testService) {
        $scope.root='initial';
        $scope.testSubmit = function () {
            testFactory.setRoot($scope)
        }
    })
.factory('testFactory', function(){
        return {
            setRoot: function(scope){
                scope.root=scope.test

            }
        }
    })

The only way to do what you want is to return a value from a factory and then bind this value to the $scope :

angular.module('testApp', [])
  .controller('HelloCtrl', function ($scope, testFactory, testService) {

    $scope.root = 'initial';

    $scope.testSubmit = function() {
      $scope.root = testFactory.setRoot();
    }
  })
  .factory('testFactory', function() {
    return {
      setRoot: function() {
        return 'Some value';
      }
    }
  });

Like I stated in the previous question you asked, $rootScope and $scope cannot be bound from a service or factory. The way you should utilize these are rather by returning a value from them which you then use in your controller. The controller is what should be binding things to the scope, not a service or factory.

In this example $scope.root will be updated with the value of what testFactory.setRoot() returns, which in this case is 'Some value' .

Here is another question which you can use to gain a better understanding:

Accessing $scope in AngularJS factory?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM