Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS中模型更新的Reinvoke函数_Javascript_Angularjs_Data Binding_Service - Fatal编程技术网

Javascript AngularJS中模型更新的Reinvoke函数

Javascript AngularJS中模型更新的Reinvoke函数,javascript,angularjs,data-binding,service,Javascript,Angularjs,Data Binding,Service,首先,如果我的术语或方法不适用,我要提前道歉——我来自结构工程背景,正试图通过一个小型宠物项目学习javascript和AngularJS 我的问题是:每当模型更新时,如何在服务中重新调用函数updateMe()。下面是一个示例代码和plunker 最初,此代码将正常运行并计算结果。如果更新了a或b,则更新后的值会传播到所有控制器,但result的值不会更新 我尝试过使用$scope.$watch(),但我无法让它工作,我也不确定这是正确的方法 在我的实际项目中,所讨论的函数依赖于myservi

首先,如果我的术语或方法不适用,我要提前道歉——我来自结构工程背景,正试图通过一个小型宠物项目学习javascript和AngularJS

我的问题是:每当模型更新时,如何在服务中重新调用函数
updateMe()
。下面是一个示例代码和plunker

最初,此代码将正常运行并计算结果。如果更新了
a
b
,则更新后的值会传播到所有控制器,但
result
的值不会更新

我尝试过使用
$scope.$watch()
,但我无法让它工作,我也不确定这是正确的方法

在我的实际项目中,所讨论的函数依赖于myservice对象的几个属性,并生成JSON数据,然后用它绘制。我希望在用户更新myservice对象的属性时,通过重新生成数据使绘图具有交互性

angular
   .module('app', []);

//some function to be evaluated when the data in myservice changes
function updateMe(x, y) {
  return x * y;
}

//Define a service (to provide data to multiple ctrls)
function MyService() {
   var myservice = this;
   myservice.a = 2;
   myservice.b = 5;
   // I am trying to get 'result' to update when any of the input parameters update
   myservice.result= updateMe(myservice.a, myservice.b); 
}
angular
  .module('app')
  .service('myservice', MyService);

// Controller that uses myservice data in the view
function FirstCtrl(myservice) {
   var vm = this;
   vm.myservice = myservice;

}
angular
   .module('app')
   .controller('FirstCtrl', FirstCtrl);

// Another Controller that uses myservice data in the view      
function SecondCtrl(myservice) {
   var vm = this;
   vm.myservice = myservice;
}
angular
   .module('app')
   .controller('SecondCtrl', SecondCtrl);

下面是一个类似于上面代码的示例

您可以使用ng change函数重新计算值

<input type="number" step="1" ng-model="first.myservice.a" ng-change="first.myservice.updateAll(first.myservice.a)">


  myservice.updateAll=function()
 {
   myservice.result = updateMe(myservice.a, myservice.b);
 }

myservice.updateAll=function()
{
myservice.result=updateMe(myservice.a,myservice.b);
}
每当模型发生变化时,
updateAll
就会触发,您可以在其中进行所有的重新计算


是工作示例。

向我们展示您使用
$watch尝试的方法,这是一种正确的方法。我尝试使用类似的方法:
$scope.$watch(vm.myservice,function(newVal,oldVal){vm.myservice.result=updateMe(vm.myservice.a,vm.myservice.b);})在其中一个控制器中。感谢您的帮助!这个解决方案在我的应用程序中有效,我现在可以实时查看我的数据了!虽然我确信有办法让$scope.$watch工作,但这似乎是最干净的方式。