使用controller as访问属性指令值

accessing attribute directive values using controller as

本文关键字:指令 属性 访问 controller as 使用      更新时间:2023-09-26

我知道如何做到没有控制器:


假设我有一个名为ngUpperCase(either true or false)

的指令
<div ng-controller="myControl" >
 <input type="text" ng-upper-case="isGiant" >
</div>

Js

myApp.directive('ngUpperCase',function(){
  return{
     restrict:'A',
     priority:0,
     link:function($scope,element,attr){
         //---to retrieve value
         var val = $scope[attr.ngUpperCase];
         var anotherVal = $scope.$eval(attr.ngUpperCase);
         $scope.$watch(attr.ngUpperCase,function(val){
            //---to watch
         })
     }
  };
})

如果我使用这样的东西,如何使指令?

<div ng-controller="myControl as ctl" >
 <input type="text" ng-upper-case="ctl.isGiant" >
</div>

由于您想要实现的目标不是很清楚,这里有一个示例,我理解您需要:根据变量将输入值更改为大写或小写:

function ngUpperCase() {
  return{
     restrict:'A',
     priority:0,
     link:function($scope,element,attr){
         //---to retrieve value
         var val = $scope[attr.ngUpperCase];
         var anotherVal = $scope.$eval(attr.ngUpperCase);
         $scope.$watch(attr.ngUpperCase,function(val){
            if(val) {
              element[0].value = element[0].value.toUpperCase();
            } else {
              element[0].value = element[0].value.toLowerCase();
            }
         })
     }
  }
}
function myController() {
  this.isGiant = true;
}
angular.module('myApp', []);
angular
    .module('myApp')
    .controller('myController', myController)
    .directive('ngUpperCase', ngUpperCase);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="myController as ctl" >
    <a href="" ng-click="ctl.isGiant = false">lower case</a><br>
    <a href="" ng-click="ctl.isGiant = true">upper case</a>
    <input type="text" ng-upper-case="ctl.isGiant" value="TeStiNg123" >
  </div>
</div>