如何使用自定义Angular指令移动此文本块?

时间:2014-09-08 22:30:46

标签: angularjs

我正在尝试按下箭头时向上或向下移动一个文本块。在按下按钮时,我遇到了修改CSS值的指令。

这是我的HTML:

    <!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.22/angular.js" data-semver="1.2.22"></script>
    <script src="app.js"></script>
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="subtitle.js"></script>
  </head>
<body ng-controller="MainCtrl">
<h1>Move Text up or down</h1>
<subtitle class="sub" pos="position">This will move when buttons are pressed</subtitle>
<br>
  Position={{position}}
  <br>
  <br>
  <p style="color:red">Click buttons to move text up or down</p>

  <i class="fa fa-chevron-up" ng-click="inc()"></i>
  <i class="fa fa-chevron-down" ng-click="dec()"></i>
  </body>

</html>

这是我的指示:

angular.module('mSystem')
    .directive('subtitle', function () {

        "use strict";

        var
            scope = {
                pos: "="
            },
            restrict = 'AE',

            link = function($scope, $element, $attrs){
                $scope.$watch('pos', function () {
                        console.log("position is: "+$scope.pos);
                        $element.css('{top:'+$scope.pos+'px;position:relative;!important}');
                        $attrs.style="top:'+$scope.pos+'px;position:relative;!important'";

                });
            };

        return {
            scope: scope,
            link: link,
            restrict: restrict
        };
    });

这是我的应用程序:

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

app.controller('MainCtrl', function($scope) {
 $scope.position=20;
 $scope.inc=function(){
   $scope.position+=1;

 }
 $scope.dec=function(){
  console.log('subtracted');
   $scope.position-=1;
 }
});

我在这里创建了一个angular.js plunker:http://plnkr.co/o99x2Z

2 个答案:

答案 0 :(得分:0)

更改CSS的语法略有不同。试试这个:

$element.css('top', $scope.pos + 'px');

Updated plunker

答案 1 :(得分:0)

您正在将字符串传递给$element.css(),而是使用对象

$element.css({ top: $scope.pos+'px', position: 'relative;!important' });

<强> Plunker