correct way to initialise scope values when the view is loaded with angularjs, ngInit?

后端 未结 1 506
你的背包
你的背包 2021-01-13 11:22

I\'ve been learning angularJs for the past few weeks and been looking at a number of large scale apps to see how things work in the real world. In most of them I have notice

相关标签:
1条回答
  • 2021-01-13 11:57

    It is bad practice because the view is initialized at a different time than the controller AND the digest cycle has to process that function, which is an unnecessary addition to that cycle. I assume you have something like:

    View:

    <div ng-init="init()">
     <span>{{thing}}</span>
    </div>
    

    Controller:

    Module.controller('viewController', function(scope){
        ...
        var init = function(){
         scope.thing = "123";
         ...
        }
        ...
    })
    

    The better practice is to do this:

    View:

    <div>
     <span ng-bind="thing"></span>
    </div>
    

    Controller:

    Module.controller('viewController', function(scope){
     scope.thing = "123";
    })
    
    0 讨论(0)
提交回复
热议问题