角 - 在指令更新范围 [英] Angular - update scope in Directive

查看:141
本文介绍了角 - 在指令更新范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有更新的指令,一个范围变种的问题,我不希望有在指令中添加HTML,是有可能只是有更新的范围变量的值。一开始活动的链接将更新各种文字/链接/图像,但首先我只是希望它更新的范围变数名称

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

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

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

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的范围名称不更新,感谢您的任何帮助。

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

推荐答案

我设法解决我自己,我最终改变它因此在控制器不更新的功能。

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

在控制器

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

          });
      });

感谢您的帮助,虽然

thanks for the help though

这篇关于角 - 在指令更新范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆