【问题标题】:Update factory from controller works but not from directive从控制器更新工厂但不是从指令更新工厂
【发布时间】:2015-09-02 08:07:03
【问题描述】:

我是 Angular 新手,遇到类似 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

【问题讨论】:

    标签: controller factory directive


    【解决方案1】:

    找到解决方案

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 2016-12-09
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      相关资源
      最近更新 更多