【问题标题】:Angular does not recognize Jquery's css function in post-link of a custom directiveAngular 在自定义指令的后链接中无法识别 Jquery 的 css 函数
【发布时间】:2017-09-19 18:17:03
【问题描述】:

我正在尝试学习 AngularJS,现在我正在使用自定义指令。

正如您在下面看到的,我正在尝试更改为特定元素的边框颜色,但是当我尝试通过链接后功能对其进行修改时,这似乎不起作用。

var app = angular.module('app',[]);

app.controller('ctr', ['$scope' , function($scope){

}]);

app.directive('mydirective', function(){

  return {
    template: '<strong>HEY</strong>',

    compile: function($tElement , $tAttributes){
      console.log($tAttributes.text + ' @ Compile');
      $tElement.css('border','1px solid black');

      return {
        pre : function($iElement , $scope , $iAttributes){
          console.log($iAttributes.text + ' @ Pre-link');
        },
        post: function($iElement , $scope , $iAttributes){
          console.log($iAttributes.text + ' @ Post-link');

          if( $iAttributes.text === "5"){
              $iElement.css('border','1px solid red');
          }
        }
      };

    },

    controller: function($element , $scope , $attrs){
      console.log($attrs.text + ' @ Controller');
    }
  };

});

角度实际返回的是

TypeError: $iElement.css 不是函数

之前,那个css函数是用来在编译级函数中改变边框颜色的。

这也是我的 html 文件,以防万一:

<html>
    <head>
        <title>Learning AngularJS</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
        <script type="text/javascript" src="compile-link.js"></script>
    </head>
    <body ng-app="app">
      <div ng-controller="ctr">
        <div mydirective text="{{i}}" ng-repeat="i in [1,2,3,4,5,6,7,8,9]"></div>
      </div>

    </body>

【问题讨论】:

    标签: javascript jquery html css angularjs


    【解决方案1】:

    postLink 函数的签名以作用域而不是元素开头,因此.css() 不是函数,因为它没有在Scope 上定义。另外,你的preLink签名也是错误的,两者都必须使用scope, elem, attr, ctrl

    compile: function compile(tElement, tAttrs, transclude) {
      return {
         pre: function preLink(scope, iElement, iAttrs, controller) { ... },
         post: function postLink(scope, iElement, iAttrs, controller) { ... }
      }
    }
    

    参考:$compile

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      相关资源
      最近更新 更多