访问控制器指令和工厂之间的数据



我已经在factory中创建了一个全局变量。我已经访问了控制器中的全局变量,但是在改变指令中的值时,它无法在控制器中更新。

我的指令是

myApp.directive('quiz', function(quizFactory) {
return {
    restrict: 'AE',
    scope: {},
    templateUrl: 'templete.html',
    controller: function($scope){
    },
    link: function(scope, elem, attrs,UserService) {
        scope.start = function() {
            UserService.var1=true;
            }
         }  
        };

My Factory is

myApp.factory('UserService', function() {
return {
    var1 : false
    };
 });

控制器是

myApp.controller('LearnSetQue', ['$scope','UserService',
function($scope,UserService){
    $scope.var2=UserService.var1;
    $scope.var3=UserService.var1;
    }
]);

Here start is button function

<button ng-click="start()">Start</button>

在这里点击开始按钮,var1应该成为真正的var1=true,var2=true and var3=true,我如何在控制器中更新。

首先,在服务中,你应该返回一个带有你想在整个应用中共享的属性的对象:

myApp.factory('UserService', function() {
var properties = { var1: false };
return {
    getProperties : function() { return properties; }
    };
 });

然后在指令

scope.start = function() {
  UserService.getProperties().var1=true;
}

在控制器中应该有:

myApp.controller('LearnSetQue', ['$scope','UserService',
function($scope,UserService){
    $scope.properties = UserService.getProperties();
]);

然后在视图中,直接引用var1

<div>{{ properties.var1 }}</div>

最新更新