【问题标题】:Angular - update scope in DirectiveAngular - 指令中的更新范围
【发布时间】:2015-01-13 00:53:56
【问题描述】:

我在更新指令中的作用域变量时遇到问题,我不想在指令中添加 HTML,是否可以只更新作用域变量的值。 get-event 链接会更新各种文本/链接/图像,但首先我只希望它更新范围 var name

索引.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!';
        });

      });

HTML 上的范围名称没有更新,感谢您的帮助。

【问题讨论】:

  • 您在控制台中看到了什么错误?您可能缺少 ng-app
  • 抱歉,ng-app 没有包含在 index.jade 中。 console.log(result); 没有错误就在 scope.name = NEW" 上方打印出对象。{{name}} 只是不更新​​

标签: angularjs scope apply


【解决方案1】:

我设法解决了自己,我最终改变了它,所以控制器中有一个函数可以进行更新。

在控制器中

     $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;
        });
    };

在指令中

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

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

          });
      });

谢谢你的帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 2013-06-04
    相关资源
    最近更新 更多