M
M
Maxim2014-11-28 13:49:41
JavaScript
Maxim, 2014-11-28 13:49:41

An example of working with directives?

Can someone share an example of a directive that would change the values ​​on the page in real time depending on the selected value from the dropdown list. That is, something like, if one value is selected, then one value is displayed in the desired area, if the other is a correspondingly different value. I'm trying to figure out the directives, but it's somehow tight.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2014-11-28
@might

Here, for example, there is a select and a directive that changes the text depending on the value of the select ( working example ):

angular.module('myApp',[]);

angular.module('myApp')
    .controller('myCtrl',[ '$scope',
        function($scope){
          $scope.options = [
            {name:'text1'},
            {name:'text2'}
          ];
          $scope.selectedText = $scope.options[0];
        }
    ])
    .directive('myDirective', [ function () {
        return {
                restrict: 'AE',
                scope: {
                    selectedValue: '=ngModel',
                },
                templateUrl: 'directive-template.html',
                link: function(scope,elem,attrs) {
                
                },
                controller: function($scope) {
                  $scope.isChosen = function(v) {
                    return $scope.selectedValue == v;
                  };
                }
            };
    }])
;

<body ng-controller="myCtrl">
    <p>Hello world!</p>
    <select ng-model="selectedText" ng-options="opt.name for opt in options"></select>
    <div ng-model="selectedText.name" my-directive=""></div>
  </body>

<div>
  <h1 ng-show="isChosen('text1')"> ТЕКСТ 1 </h1>
  <h1 ng-show="isChosen('text2')"> ТЕКСТ 2 </h1>
</div>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question