在Angular的dom元素上使用两次ng-controller

Using ng-controller twice on dom elements in Angular

本文关键字:ng-controller 两次 Angular dom 元素      更新时间:2023-09-26

我必须在两个dom元素上使用相同的控制器。我了解到在两个元素上使用ng-controller将实例化两个实例。我必须在这两个实例之间共享一个变量。我所做的就是创建一个服务并在控制器中分配watch来观察服务中的变量

但是我没有看到第二个控制器得到更新。

下面是我试图让它工作的jsfiddle链接。

http://jsfiddle.net/jnj6y/251/

JS代码:

var myModule = angular.module('myModule', []);
myModule.controller('mainCtrler',function($scope){
              // $scope.dummy="main" 
                });
myModule.controller('SFCtrler',function($scope,highlightService) {
$scope.dummy="hi";
 $scope.submit = function(){
     highlightService.setDummy("howdy");
        $scope.dummy=highlightService.getDummy();
    };
$scope.$watch(function () {highlightService.getDummy(); },function(newVal, oldVal) { 
        alert(highlightService.getDummy());
        $scope.dummy=highlightService.getDummy();   
        },
        true);  
    });
myModule.service('highlightService', function() {
var dummy ='default';
var setDummy = function(input){
    dummy = input;
}
var getDummy = function(){
    return dummy;
}
 return {       
      setDummy: setDummy,
      getDummy: getDummy    
};
});
HTML代码:

<div ng-controller="mainCtrler">
<div ng-controller="SFCtrler" > 
     <p>{{dummy}}</p>
            <form id='sf' ng-submit="submit();" >
                <input ng-model="SearchTerm" placeholder="Search current record"  type="text" >
            </form>
        </div>   
<div ng-controller="SFCtrler" > 
<p>{{dummy}}</p>                
        </div>   
</div>

你们能指出我缺少什么吗

function () {highlightService.getDummy(); }应为:

function() {
  return highlightService.getDummy();
}

需要返回一个值给$scope.$watch

完整更新的监视程序代码:

$scope.$watch(function () {
  return highlightService.getDummy();
}, function(newVal, oldVal) { 
  $scope.dummy = newVal;  
}, true);  

我已经更新了您的jsfiddle: http://jsfiddle.net/zwa3s77c/您不希望使用原始变量作为作用域变量。

var myModule = angular.module('myModule', []);
myModule.controller('mainCtrler',function($scope){
});
myModule.controller('SFCtrler',function($scope,highlightService) {
    $scope.dummy={val: "hi"};
    $scope.submit = function(){
        highlightService.setDummy("howdy");
        $scope.dummy=highlightService.getDummy();
    };
    $scope.$watch(function () {
        highlightService.getDummy();
        }, function(newVal, oldVal) { 
            alert(highlightService.getDummy().val);
            $scope.dummy=highlightService.getDummy();   
        }, true);  
});
myModule.service('highlightService', function() {
    var dummy ={val:'default'};
    var setDummy = function(input){
        dummy.val = input;
    }
    var getDummy = function(){
        return dummy;
    }
     return {       
          setDummy: setDummy,
          getDummy: getDummy    
    };
});

这里有更多的参考:http://www.codelord.net/2014/05/10/understanding-angulars-magic-dont-bind-to-primitives/