简体   繁体   English

Angular和JavaScript范围用于变量访问

[英]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? 从视图可以访问testabc吗? 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. 您可以使用angular ng-init指令。

;(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. PS是的,您的selectedMonth在视图中可见。

Anything you bind to the scope will be accessible in the view. 您绑定到范围的任何内容都将在视图中访问。 Scope is the glue between your controller and your HTML view. 范围是控制器和HTML视图之间的粘合剂。 If you need only the month to be accessible just bind it to vm. 如果您只需要访问月份,则将其绑定到vm。

vm.selectedMonth= dateRef.getMonth();

This line would be just enough. 这条线就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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