【问题标题】:custom directive function not working angularjs自定义指令功能不起作用
【发布时间】:2015-05-22 03:19:54
【问题描述】:

我有这段代码,但是当用户在输入中写入颜色时,新元素的背景颜色应该改变但不起作用,我做错了什么?

<div ng-app="mainApp" ng-controller="MainCtrl">
         <input type="text" ng-model="color" placeholder="Enter a color" />
         <hello-world/>
   </div>
   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
   <script>
      var mainApp = angular.module("mainApp", []);

      mainApp.directive('helloWorld', function() {
         return {
    restrict: 'AE',
    replace: true,
    template: '<p style="background-color:{{color}}">Hello World',
    link: function(scope, elem, attrs) {
      elem.bind('click', function() {
        elem.css('background-color', 'white');
        scope.$apply(function() {
          scope.color = "white";
        });
      });
      elem.bind('mouseover', function() {
        elem.css('cursor', 'pointer');
      });
    }
  };
});
 </script>

【问题讨论】:

标签: angularjs apply directive


【解决方案1】:

关闭你的模板标签并从那里删除内联样式。 你也应该使用 elem.on() 而不是 elem.bind()

var mainApp = angular.module("mainApp", []);

      mainApp.directive('helloWorld', function() {
         return {
    restrict: 'AE',
    template: '<input type="text" placeholder="Enter a color" ng-model="color"/><p>Hello World</p>',
    link: function(scope, elem, attrs) {
      scope.color = elem.find('input').val();
      scope.$watch('color', function(newVal, oldVal){
        if(oldVal === newVal) return;
    
        elem.find('p').addClass(scope.color +'');
        
      });
      elem.on('mouseover', function() {
        elem.find('input').css('cursor', 'pointer');
      });
    }
  };
});
.red {
  background-color: red;
  }
.blue {
  background-color: blue;
  }
<!doctype html>
  <html ng-app="mainApp">
    <head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
      </head>
    <body>
      <hello-world></hello-world>
      </body>
    </html>

请在示例中输入“红色”或“蓝色”。

【讨论】:

  • &lt;input&gt; 在哪里?我认为这对 OP 的应用程序至关重要
  • 您可以在我的代码底部单击蓝色按钮“运行代码 sn-p”来测试它。
猜你喜欢
  • 2018-06-01
  • 2015-11-02
  • 1970-01-01
  • 2019-08-15
  • 2016-12-29
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多