2015-09-02 62 views
0

Im新的角度和像this類似的問題,但該解決方案不適合我。更新從控制器的工廠工作,但不是從指令

我使用兩個控制器,這些控制器可以訪問工廠,如果更新出廠值,兩個控制器也更新它們的值。

但是,如果我使用指令更新出廠值控制將不會更新。

var app = angular.module('myApp', []); 

app.factory('testFactory', function() { 
    var countF = 1; 
    return { 
     getCount: function() { 

      return countF; 
     }, 
     incrementCount: function() { 
      countF++; 
      return countF; 
     } 
    } 
}); 

app.controller('FactoryCtrl',function($scope,testFactory){ 
    $scope.countFactory = testFactory.getCount; 
    $scope.clickF = function() { 
     $scope.countF = testFactory.incrementCount(); 
    }; 
}); 

app.controller('anotherCtrl',function($scope, testFactory) { 
    $scope.countFactory = testFactory.getCount; 
    $scope.clickF = function() { 
     $scope.countF = testFactory.incrementCount(); 
    }; 
}); 

app.directive("d1", function (testFactory) { 

    return { 
     restrict: "C", 
     link: function ($scope, element, attr) { 
       $scope.$apply(function() { 
        element.bind('click', function() { 
         testFactory.incrementCount(); 
        }) 
       }); 
     } 
    }; 
}); 

See in JS Fiddle

回答

0

發現的解決方案

app.directive("d1", function (testFactory) { 
    return { 
     restrict: "C", 
     scope: false, 
     link: function ($scope, element, attr) { 
      element.bind('click', function() { 
       testFactory.incrementCount(); 
       $scope.$apply(); 
      }); 

     } 
    }; 
}); 
相關問題