簡體   English   中英

從工廠功能設置控制器范圍變量的最佳實踐?

[英]best practice to set controller scope variable from factory function?

我下面有工作代碼,可從工廠“ testFactory”函數setRoot()設置控制器“ HelloCtrl”作用域變量“ root”。 我在HTML中將ng-submit =“ testSubmit()”與ng-model =“ test”結合使用。 恐怕這不是最佳做法,您還建議什么?

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

            }
        }
    })

進行所需操作的唯一方法是從工廠返回一個值,然后將此值綁定到$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';
      }
    }
  });

就像我在上一個問題中所說的那樣, $rootScope$scope不能從服務或工廠綁定。 您應該利用它們的方式是從它們中返回一個值,然后在控制器中使用它。 控制器應該將事物綁定到示波器,而不是服務或工廠。

在此示例中, $scope.root將使用testFactory.setRoot()返回的值進行更新,在本例中為'Some value'

這是您可以用來更好理解的另一個問題:

在AngularJS工廠中訪問$ scope?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM