简体   繁体   中英

Angular and javascript scope for variable access

In the view I'm declaring the controller like so:

<div data-ng-controller="myController as myCtrl">
     {{myCtrl.selectedMonth}}
</div>

I want to be able to access a month in the view, but I don't want the date object to be accessible from the view. Would this do it? Is testabc accessible from the view? Is this a good way to have privately scoped variables on the controller?

;(function() {
    'use strict';

    angular
        .module('myApp')
        .controller('myController', myController);

    function myController() {

        var testabc = 'can you see this';
        var dateRef = new Date();
        var vm = this;

        angular.extend(vm, {
                selectedMonth: undefined
        });

        init();

        function init(){

            vm.selectedMonth = dateRef.getMonth();
        }


    }

}());

First dont trigger init in controller as it sometimes creates issues. you can use angular ng-init directive.

;(function() {
    'use strict';

    angular
        .module('myApp')
        .controller('myController', myController);

    function myController() {

        var testabc = 'can you see this';
        var dateRef = new Date();
        var vm = this;

        angular.extend(vm, {
                selectedMonth: undefined,
                init:init
        });



        function init(){

            vm.selectedMonth = dateRef.getMonth();
        }


    }

}());

and your view will be

<div data-ng-controller="myController as myCtrl" ng-init="myCtrl.init()">
     {{myCtrl.selectedMonth}}
</div>

PS yes your selectedMonth is visible in view.

Anything you bind to the scope will be accessible in the view. Scope is the glue between your controller and your HTML view. If you need only the month to be accessible just bind it to vm.

vm.selectedMonth= dateRef.getMonth();

This line would be just enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM