在指令

时间:2017-11-03 15:32:15

标签: javascript jquery angularjs

我有一个像这样的控制器:

myApp.controller('WizardController', function ($scope, $http) {

$scope.user = {
    addressline1: null,
    cobuyer: null,
    validate: null,
    cobuyerfirstname: null,
    cobuyerlastname: null,
    cobuyeremail: null,
    cobuyerdob: null,
    cobuyeraddressline1: null,
    cobuyeraddressline2: null,
    cobuyercity: null,
    cobuyerprovince: null,
    cobuyerpostalcode: null,
    cobuyerphone: null,
    dobString: null,
    cobuyerDobString: null,
    isWaitList: false
};

});

我在下面添加了这个指令:

myApp.directive('checkbox', function () {
    return {
        restrict: 'A',
        replace: false,
        transclude: true,
        scope: {
            user: '='
        },
        template: '<label for="addressSame" class="form-label col-md-2" style="width: auto;">Same as Buyers Address</label><input type="checkbox" name="addressSame" ng-click="isSameAddress()" ng-model="isChecked" />',
        link: function (scope, element, attrs) {
            // Initialize to unchecked
            scope.isChecked = false;

        },
        controller: function ($scope) {

            $scope.isSameAddress = function () {

                console.log($scope.isChecked);

                if ($scope.isChecked == true) {
                    console.log($scope.user);
                }
                else {

                }
            }

        }
    }
});

现在我的复选框显示为应该,我可以检查它并从scope.isChecked获取true或false。我现在正试图从$ scope.user获取项目,但它表示未定义。我是Angular JS的新手,我不知道如何解决这个问题......如何获得控制器中定义的元素?

我也试过这个,仍未定义:

myApp.directive('checkbox', function () {
    return {
        restrict: 'A',
        replace: false,
        transclude: true,
        scope: {
            user: '='
        },
        template: '<label for="addressSame" class="form-label col-md-2" style="width: auto;">Same as Buyers Address</label><input type="checkbox" name="addressSame" ng-click="isSameAddress()" ng-model="isChecked" />',
        link: function (scope, element, attrs) {
            // Initialize to unchecked
            scope.isChecked = false;

        },
        controller: function ($scope, $http, $rootScope) {

            $scope.isSameAddress = function () {

                console.log($scope.isChecked);

                if ($scope.isChecked == true) {
                    console.log($rootScope.user);
                }
                else {

                }
            }

        }
    }
});

4 个答案:

答案 0 :(得分:1)

那是因为$scope仅在控制器本身内可见; 你可以使用$rootScope(只是说它是一个全局变量); 尝试从$scope.user更改为$rootScope.user

答案 1 :(得分:1)

试试这个

myApp.controller('WizardController', ['$scope', function ($scope, $http) {

$scope.user = {
    addressline1: null,
    cobuyer: null,
    validate: null,
    cobuyerfirstname: null,
    cobuyerlastname: null,
    cobuyeremail: null,
    cobuyerdob: null,
    cobuyeraddressline1: null,
    cobuyeraddressline2: null,
    cobuyercity: null,
    cobuyerprovince: null,
    cobuyerpostalcode: null,
    cobuyerphone: null,
    dobString: null,
    cobuyerDobString: null,
    isWaitList: false
};

}]);

答案 2 :(得分:0)

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

app.directive('checkbox', function () {
    return {
        restrict: 'A',
        replace: false,
        transclude: true,
        $scope: {
            user: '='
        },
        template: '<label for="addressSame" class="form-label col-md-2" style="width: auto;">Same as Buyers Address</label><input type="checkbox" name="addressSame" ng-click="isSameAddress()" ng-model="isChecked" /> <span ng-if="isChecked"> {{user|json}}</span>',
        link: function ($scope, element, attrs) {
            // Initialize to unchecked
            $scope.isChecked = false;
            console.log($scope.user)

        },
        controller: function ($scope) {

            $scope.isSameAddress = function () {

                console.log($scope.isChecked);

                if ($scope.isChecked === true) {
                    console.log($scope.user);
                }
                else {

                }
            }

        }
    }
});

app.controller('MainCtrl', function ($scope, $http) {
  $scope.user = {
    addressline1: null,
    cobuyer: null,
    validate: null,
    cobuyerfirstname: null,
    cobuyerlastname: null,
    cobuyeremail: null,
    cobuyerdob: null,
    cobuyeraddressline1: null,
    cobuyeraddressline2: null,
    cobuyercity: null,
    cobuyerprovince: null,
    cobuyerpostalcode: null,
    cobuyerphone: null,
    dobString: null,
    cobuyerDobString: null,
    isWaitList: false
};
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p checkbox="user">Hello</p>
  </body>

</html>

答案 3 :(得分:0)

由于您没有提供任何其他代码,因此很难确切知道您在做什么。所以我做了一些假设:

  • 我认为您的控制器WizardController是外部的 控制器。
  • 我认为你确实没有使用过翻译 因为你的模板没有使用它。所以我删除了transclude: true 来自指令。
  • 我格式化了代码以适应我的风格。我发现更容易打破我的 角度注册码的功能。把事情分组在一起。 如果你打算这样做,我还添加了代码来处理缩小。
  • 我从未将我的控制器代码嵌入到我的指令中。这符合 Single Responsibility Principle 好一点。

我将在下面提供更多详细信息。

这是我的代码:

<!DOCTYPE html>
<html ng-app="myApp">
  <head>
    <title>AngularJS Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
    <script>
    // Controller code for application
    AppController.$inject = ['$scope', '$http']; // <- This is needed only if you plan to minify your JS code.
    function AppController($scope, $http) {
      $scope.user = {
        addressline1: '', // <-- Since these values will display in the HTML use an empty string instead of null
        cobuyer: '',
        validate: '',
        cobuyerfirstname: 'John',
        cobuyerlastname: 'Smith',
        cobuyeremail: 'myEmail@example.com',
        cobuyerdob: '',
        cobuyeraddressline1: '123 Some Street',
        cobuyeraddressline2: '',
        cobuyercity: 'Anchorage',
        cobuyerprovince: '',
        cobuyerpostalcode: '99501',
        cobuyerphone: '',
        dobString: '',
        cobuyerDobString: '',
        isWaitList: false
      };
    }

    // Controller code for directive `checkbox`
    CheckboxController.$inject = ['$scope']; // <- This is needed only if you plan to minify your JS code.
    function CheckboxController($scope) {
      $scope.isChecked = false; // <-- Put all scope variables into the controller.

      $scope.isSameAddress = function () { // <-- put all of your scope functions in the controller.
        console.log('$scope.isChecked', $scope.isChecked);

        if ($scope.isChecked == true) {
          console.log('$scope.user', $scope.user);
        }
        else {

        }
      }
    }

    // Directive code for attribute `checkbox`
    function checkboxDirective() {
      return {
        controller: 'CheckboxController', // <-- I link to my controller and avoid adding the controller code here.
        restrict: 'A',
        replace: false,
        scope: {
          user: '='
        },
        template: '<label for="addressSame" class="form-label col-md-2" style="width: auto;">Same as Buyers Address</label><input type="checkbox" name="addressSame" ng-click="isSameAddress()" ng-model="isChecked" />'
      }
    }

    // Angular registration code
    var myApp = angular.module('myApp', []);

    myApp.controller('AppController', AppController);
    myApp.controller('CheckboxController', CheckboxController);
    myApp.directive('checkbox', checkboxDirective);
    </script>
  </head>
  <body ng-controller="AppController">
    <div checkbox user="user"></div>
  </body>
</html>

在您的示例中,您没有向我们展示您如何获得user指令。根据您的代码示例,它应该通过user属性传入。像这样:

<div checkbox user="user"></div>

由于您使用的是基于Attribute的指令,因此您也可以使用checked属性而不是user属性,如下所示:

// Directive code for attribute `checkbox`
function checkboxDirective() {
  return {
    controller: 'CheckboxController', // <-- I link to my controller and avoid adding the controller code here.
    restrict: 'A',
    replace: false,
    scope: {
      user: '=checkbox'
    },
    template: '<label for="addressSame" class="form-label col-md-2" style="width: auto;">Same as Buyers Address</label><input type="checkbox" name="addressSame" ng-click="isSameAddress()" ng-model="isChecked" />'
  }
}

这将允许您通过user属性将外部控制器的checkbox值添加到您的指令中。然后,通过$scope.user属性在指令JS代码中访问此值。像这样:

<div checkbox="user"></div>