簡體   English   中英

通過angularJS設置並獲取價值

[英]Set and get value with factory, angularJS

這是一項服務:

myApp.factory('myService', function() {
    var test = 5;

    return{
      setTestVal: function(val){
        test = val;
      },
      getTestVal: function(){
        return test;      
      }
    }    
});

這是我的控制器。 一個獲得值,然后設置它

function MyCtrl($scope, myService) {
    $scope.test = myService.getTestVal();
}

function SetCtrl($scope, myService){
    $scope.newTestVal = '';
    $scope.setTestVal = function(val){
      myService.setTestVal(val)
    }
}

但是,當我設置該值時,視圖不會更新。

小提琴: http : //jsfiddle.net/HB7LU/7036/

這是設置和獲取價值的錯誤方法嗎?

不,這種方法非常好,但是視圖不知道何時設置新值,您必須在共享屬性上設置$watch

$scope.$watch(function() {
    return myService.getTestVal();
}, function(value) {
    $scope.test = value;
});

小提琴: http : //jsfiddle.net/HB7LU/7041/

您甚至可以在沒有$ watch的情況下完成此操作,請檢查我從您修改的小提琴:

var myApp = angular.module('myApp',[]);
myApp.factory('myService', function() {
    var test = 5;
    var obj = {
        test : 5
    }

    return{
      setTestVal: function(val){
        test = val;
        obj.test = val;
      },
      getTestVal: function(){
        return test;      
      },
      data : obj
    }


});

function MyCtrl($scope, myService) {
    $scope.test = myService.getTestVal();
    $scope.data = myService.data;
}

function SetCtrl($scope, myService){
    $scope.newTestVal = '';
    $scope.setTestVal = function(val){
      myService.setTestVal(val)
    }
}

http://jsfiddle.net/no9rv2nb/

暫無
暫無

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

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