我是棱角分明的新手并且遇到类似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();
})
});
}
};
});
答案 0 :(得分:0)
找到解决方案
app.directive("d1", function (testFactory) {
return {
restrict: "C",
scope: false,
link: function ($scope, element, attr) {
element.bind('click', function () {
testFactory.incrementCount();
$scope.$apply();
});
}
};
});