美文网首页我爱编程
angular $scope, vm,angular.exten

angular $scope, vm,angular.exten

作者: 滚石_c2a6 | 来源:发表于2018-04-18 17:22 被阅读20次

    A better way to $scope, angular.extend, no more “vm = this”
    参考:https://toddmotto.com/a-better-way-to-scope-angular-extend-no-more-vm-this/

    [Using angular.extend]

    When you start having to bind a lot of things, we repeat vm so many times and end up with vm.* references all over our code. We don’t really need to bind directly to the this value, JavaScript can work on its own (such as updating var foo = {}; locally in a callback rather than vm.foo) for instance. An example with lots of vm.* bindings:

    function MainCtrl () {
    
      var vm = this;
    
      function doSomething1() {}
      function doSomething2() {}
      function doSomething3() {}
      function doSomething4() {}
      function doSomething5() {}
      function doSomething6() {}
    
      // exports
      vm.doSomething1 = doSomething1;
      vm.doSomething2 = doSomething2;
      vm.doSomething3 = doSomething3;
      vm.doSomething4 = doSomething4;
      vm.doSomething5 = doSomething5;
      vm.doSomething6 = doSomething6;
    }
    
    angular
      .module('app')
      .controller('MainCtrl', MainCtrl);
    
    <div ng-controller="Shell as vm">
      <h1></h1>
      <article ng-controller="Customers as vm">
        <h2></h2>
        <ul ng-repeat="c in vm.customers">
          <li></li>
        </ul>
      </article>
    </div>
    

    This isn’t a new idea, as we all know angular.extend, but I came across this article from Modus Create which gave me the idea to completely drop all vm references given my current Angular Controller strategy/pattern. Their examples actually use angular.extend($scope, {...});, whereas my examples all adopt the controllerAs syntax.

    Here’s a quick example dropping vm references and just binding to this:

    function MainCtrl () {
      
      // private
      function someMethod() {
    
      }
    
      // public
      var someVar = { name: 'Todd' };
      var anotherVar = [];
      function doSomething() {
        someMethod();
      }
      
      // exports
      angular.extend(this, {
        someVar: someVar,
        anotherVar: anotherVar,
        doSomething: doSomething
      });
    }
    
    angular
      .module('app')
      .controller('MainCtrl', MainCtrl);
    

    相关文章

      网友评论

        本文标题:angular $scope, vm,angular.exten

        本文链接:https://www.haomeiwen.com/subject/zucbkftx.html