Angular - update scope in Directive

2019-08-28 08:08发布

问题:

I'm having problems updating a scope var in a directive, I don't want to have to add HTML in the directive, is it possible to just have the value of the scope var updated. The get-event links will update a variety of text / links / images, but first I just want it to update the scope var name

Index.jade

   div(ng-controller='AppCtrl')
        h2 Hello {{name}}
        a(href={{link}}) test

   a.playlist(get-event rel='1000') 1000
   br 
   br
   a.playlist(get-event rel='2000') 2000
   br
   br
   a.playlist(get-event rel='3000') 3000

directive.js

    angular.module('myApp.directives', [])
      .directive('getEvent',  function($q, $http, $templateCache){
      return {
          restrict: 'A',
          scope: true,
          link: function (scope, element, attrs) {

                    function loadData() {

                            var refId = attrs.rel;
                            console.log(refId);

                        $http.get('/api/event/'+refId, {
                           // cache: $templateCache
                        }).then(function(result) {

                              console.log(result);
                               scope.name = "NEW";

                        });

                    }

                    element.bind('click', function(event) {

                        scope.$apply(function() {
                             loadData();
                        });
                    });
            }
          }
        });

controller.js

     angular.module('myApp.controllers', []).
      controller('AppCtrl', function ($scope, $http) {

        $http({
          method: 'GET',
          url: '/api/event/1000'
        }).
        success(function (data, status, headers, config) {
          $scope.name = data.title;
        }).
        error(function (data, status, headers, config) {
          $scope.name = 'Error!';
        });

      });

The scope name on the HTML doesn't update, thanks for any assistance.

回答1:

I managed to solve myself, I ended up changing it so there is a function in controller that does the update.

in controller

     $scope.update = function(id) {

           //this is just a service factory to do the http request
          updateEvent.getDetails(id).success(function (result) {

            $scope.name =result.title;
        });
    };

in directive

    element.bind('click', function(event) {

          scope.$apply(function() {
              scope.update(refId);

          });
      });

thanks for the help though