test1

by David V.

HTML

<div ng-app="tst">
  <div ng-controller="Ctrl">
    An input with the directive:<br>
    <input ng-model="inp" tst-msg="message" />
      <button ng-click='clear()'>clear</button>
    <br><br><br><br><br><br>
    Add message to the div :<br>
    <input ng-model="msg">
    <button ng-click="add()">add</button><br>
    Remove messages :
    <button ng-click="remove()">remove</button>
  </div>
</div>

CSS

.msg {
    border : 2px solid red;
    border-radius:5px;
    background-color: white;
    opacity:0.8;
}

JavaScript

function Ctrl($scope, $rootScope) {
    $scope.msg="";
    $scope.message = [];
    $scope.inp="zz";
    $scope.add = function() {
        if ($scope.msg) {
            var l = $scope.message.length;
            $scope.message.push({i:l,txt:$scope.msg});
            console.log($scope.message);
        }
    };
    $scope.remove=function(){
        $scope.message=[];
    }
    $scope.clear=function(){
        $scope.inp="";
    }
}

angular.module('tst', [])
.directive('tstMsg', ['$compile','$timeout',function($compile,$timeout){
    var template = "<div class='msg' ng-hide='!tstMsg.length'><ul><li ng-repeat='msg in tstMsg track by msg.i'><span ng-bind='msg.txt'></span></li></ul></div>";

    var link = function(scope,element,attrs,ngModel) {
        var a=$compile(template)(scope);
        var px=element.prop("offsetLeft");
        var py=element.prop("offsetTop");
        py+=element.prop("offsetHeight");
        console.log(px,py);
        a.css({position:"absolute",left:px+"px",top:py+"px"});
        element.parent().append(a);
        console.log("link called : "+attrs.ngModel);
        scope.$parent.$watch(attrs.ngModel, function (v) {
            console.log('value changed, new value is: ' + v);
            scope.tstMsg=[];
        });
        element.on('focus',function(){
            scope.$apply(function(){
                console.log("focus !");
                scope.tstMsg=[];
            })
        });
    };

    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            tstMsg: '=',
            model: '=ngModel'
        },
        link: link
    };
}]);