Updating a scope variable from a directive

Variable areas updated by the directive are not reflected where we have {{variable}}on the page, however they appear as updated when I do console.log(scope).

<script>
    var demoApp = angular.module('demoApp', []);

    demoApp.controller('demoController', function demoController($scope) {
      $scope.myElementId ="abcd";
      $scope.updateVals = function() {
        $scope.myElementClass = "";
      };
    });

    demoApp.directive('demoSelect', function() {
      return {
        restrict: 'A',
        controller: 'demoController',
        link: function(scope, element, attrs, controller) {
          element.on("click", function(event) {
            event.stopImmediatePropagation();
            event.preventDefault();
            scope.ele = angular.element(event.target);
            angular.element(".selected").removeClass("selected");
            $(scope.ele).addClass("selected");
            var mm = $(scope.ele).get(0);
            scope.myElementId = $(scope.ele).attr("id");
            scope.myElementClass = $(scope.ele).attr("class");
            scope.myElementType = mm.tagName;
          });
        }
      };
    });
  </script>

Here is the plunker for him . What am I missing?

+4
source share
3 answers

There were several errors in your demo:

  • jQuery was downloaded after Angular. You should always download jQuery to Angular, so the latter knows and can take advantage of the former.

  • , camelCase, , . , demoApp demoController demo-app demo-controller HTML.

  • Angular - ( ) Angular ( jQuery), , Angular ( , ), $apply().

  • ( , ): jQuery jQuery. .


, :

element.on('click' , function(evt) {
    evt.stopImmediatePropagation();
    evt.preventDefault();

    $('.selected').removeClass('selected');
    element.addClass('selected');
    scope.$apply(function () {
        scope.myElementId    = attrs.id;
        scope.myElementClass = attrs.class;
        scope.myElementType  = element.prop('tagName');
    });
});

. woking.

+5

scope.$apply:

scope.$apply(function(){
    scope.ele = angular.element(event.target);
    angular.element(".selected").removeClass("selected");
    $(scope.ele).addClass("selected");
    var mm = $(scope.ele).get(0);
    scope.myElementId = $(scope.ele).attr("id");
    scope.myElementClass = $(scope.ele).attr("class");
    scope.myElementType = mm.tagName;
});

, , angularjs dom

+4

:

link: function(scope, element, attrs, controller) {
      element.on("click", function(event) {

        event.stopImmediatePropagation();
        event.preventDefault();

        $(".selected").removeClass("selected");
        $(element).addClass("selected");

        var mm = $(element).get(0);
        scope.myElementId = $(element).attr("id");
        scope.myElementClass = $(element).attr("class");
        scope.myElementType = mm.tagName;

      });
    }

. .

+2

All Articles