zoukankan      html  css  js  c++  java
  • AngularJS controller as vm方式

      从AngularJS1.20开始引入了Controller as 新语法,以前版本在Controller 中必须注入$scope这个服务,才能在视图绑定中使用这些变量,$scope不是那么POJO(普通纯粹的JavaScript对象)。

    一、基本用法

      1.20以前版本:

    angular.module("myModule").controller("MyController", function($scope){
        $scope.title = "Angular";
    });
    <div ng-app="myModule" ng-controller="MyController">
        hello:{{tittle}}!
    </div>

      1.20及以后版本

    angular.module("myModule").controller("MyController", function(){
        this.title = "Angular";
    });
    <div ng-app="myModule" ng-controller="MyController as demo">
        hello:{{demo.tittle}}!
    </div>

      推荐用法:

    angular.module("myModule").controller("MyController", function(){
         var vm = this;
         vm.title = "Angular";
         return vm;
    });

      分析源码,得知Controller对象实例以as别名放在$scope上,所以视图模板能够访问到。

    二、路由中的Controller as

    三、指令中的Controller as

      

      

      问题:scope:{}属性声明的变量还是自动绑定到$scope,为了解决这个问题,1.3版本引入了属性bindToController:true,scope变量自动绑定到vm。

      

  • 相关阅读:
    [gym102832J]Abstract Painting
    [atARC070E]NarrowRectangles
    [atARC070F]HonestOrUnkind
    Cupid's Arrow[HDU1756]
    Surround the Trees[HDU1392]
    TensorFlow-正弦函数拟合
    某新版本不兼容老版本代码的语言的一点基础了解
    TensorFlow安装
    离散快速傅里叶变换
    2016"百度之星"
  • 原文地址:https://www.cnblogs.com/shawnhu/p/8521368.html
Copyright © 2011-2022 走看看