如何在离子控制器内部使用指令范围变量?

时间:2017-02-02 06:35:52

标签: javascript angularjs ionic-framework

我正在研究ionic framework ....我想在控制器中使用指令范围变量?尝试了stack overflow中讲述的不同选项或答案,但没有一个对我有用......所以我再次提出这个问题。

这是我的代码:

.directive('simpleCaptcha', function() {
    return {
        restrict: 'E',
        scope: { valid: '=' },
        template: '<input ng-model="a.value" ng-show="a.input" style="width:2em; text-align: center;"><span ng-hide="a.input">{{a.value}}</span>&nbsp;{{operation}}&nbsp;<input ng-model="b.value" ng-show="b.input" style="width:2em; text-align: center;"><span ng-hide="b.input">{{b.value}}</span>&nbsp;=&nbsp;{{result}}',
        controller: function($scope) {

            var show = Math.random() > 0.5;

            var value = function(max){
                return Math.floor(max * Math.random());
            };

            var int = function(str){
                return parseInt(str, 10);
            };

            $scope.a = {
                value: show? undefined : 1 + value(4),
                input: show
            };
            $scope.b = {
                value: !show? undefined : 1 + value(4),
                input: !show
            };
            $scope.operation = '+';

            $scope.result = 5 + value(5);

            var a = $scope.a;
            var b = $scope.b;
            var result = $scope.result;

            var checkValidity = function(){
                if (a.value && b.value) {
                    var calc = int(a.value) + int(b.value);
                    $scope.valid = calc == result;
                } else {
                    $scope.valid = false;
                }
                $scope.$apply(); // needed to solve 2 cycle delay problem;
            };


            $scope.$watch('a.value', function(){    
                checkValidity();
            });

            $scope.$watch('b.value', function(){    
                checkValidity();
            });



        }
    };
});
.controller('DashboardCtrl', function($scope, $ionicConfig, $http, $ionicPopup, $ionicModal) {
alert($scope.valid);
});

0 个答案:

没有答案