2016-07-23 54 views
0

我有一個函數make_value_summary,通常會對$scope字段進行摘要。在這裏,我使用它來構造location_summary,綁定到通過ng-bind的視圖。每更新字段street,suburbstate,即更新location_summary

$scope.location_summary = function() { 
    var fields = [ 
     'street', 
     'suburb', 
     'state', 
    ]; 
    return make_value_summary(fields, $scope, 'Location?'); 
}; 

function make_value_summary(fields, $scope, initial) { 
    var summary = ''; 
    fields.forEach(function(field) { 
     if ($scope[field] && $scope[field] !== '0') { 
      if (summary) { 
       summary = summary + ', ' + $scope[field]; 
      } 
      else { 
       summary = $scope[field]; 
      } 
     } 
    }); 
    if (summary) { 
     return summary[0].toUpperCase() + summary.substring(1); 
    } 
    else { 
     return initial; 
    } 
} 

問題1:如何location_summary得到動態更新的,從我在它看起來像make_value_summary代碼最初看起來應該當第一次被分配location_summary只能執行一次。

問題2:我想通過服務將location_summary綁定到視圖的完全不同的部分。我應該如何去附加location_summary到服務Location。我試過使用$watch但沒有成功。

$scope.$watch('location_summary', function(newValue, oldValue) { 
    // Just gives unevaluated reference to location_summary function 
    console.log(newValue); 
    console.log(oldValue); 
}); 

EDIT

由 '計算' 中相應的手錶功能,即在'location_summary()'傳遞給$watch()得到的溶液至2。仍然想回答我的第一個問題!

回答

0

根據您的代碼,請運行此代碼段。

angular.module("app",[]) 
 
.controller("appController",appController); 
 

 
appController.$inject=["$scope"]; 
 
function appController($scope){ 
 
$scope.location_summary = function() { 
 
    var fields = [ 
 
     'street', 
 
     'suburb', 
 
     'state', 
 
    ]; 
 
    return make_value_summary(fields, $scope, 'Location?'); 
 
}; 
 

 
function make_value_summary(fields, $scope, initial) { 
 
    var summary = ''; 
 
    fields.forEach(function(field) { 
 
     if ($scope[field] && $scope[field] !== '0') { 
 
      if (summary) { 
 
       summary = summary + ', ' + $scope[field]; 
 
      } 
 
      else { 
 
       summary = $scope[field]; 
 
      } 
 
     } 
 
    }); 
 
    if (summary) { 
 
     return summary[0].toUpperCase() + summary.substring(1); 
 
    } 
 
    else { 
 
     return initial; 
 
    } 
 
} 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 

 
<body ng-app="app" ng-controller="appController"> 
 
    
 
    <input ng-model="street"> 
 
    <input ng-model="suburb"> 
 
    <input ng-model="state"> 
 
    
 
    {{location_summary()}} 
 
    </body>