简体   繁体   English

范围更改时如何显示模板[Angular指令]

[英]How to display template when scope change [Angular directive]

Here is my directive: 这是我的指令:

function ajaxMessageData()
{
    var ajaxMessage = {
        link: link,
        restrict: "EA",
        template: "success",
        scope: {
            success: '='
        }
    };

    return ajaxMessage;

    function link(scope, elm, attrs)
    {

            console.log(scope.success);
            scope.$watch(attrs.success, function (newValue) {
                console.log("Changed to " + newValue);
            });

    }
}

and in html: 并在html中:

<ajax-message success="vm.message"></ajax-message>

Problem is with scope inside directive I get initial message from vm.message (it is my controller var) but when my vm.message change it not detectd in directive... Also I would like to template show only if I get success message from vm.success . 问题是指令内部的作用域我从vm.message (它是我的控制器var)收到初始消息,但是当我的vm.message更改时在指令中未检测到它。 vm.success Anyone know how to accomplish this? 有人知道如何做到这一点吗? Thanks 谢谢

  1. You're passing the wrong argument to the $watch . 您将错误的参数传递给$watch It should be an expression -- not the value of the attrs object. 它应该是一个表达式-而不是attrs对象的值。
  2. You can use the ng-if directive to control visibility. 您可以使用ng-if指令来控制可见性。
  3. Not sure if this is intended, but the success template maybe needs a curly binding: "{{ success }}" 不确定是否要这样做,但是成功模板可能需要卷曲的绑定: "{{ success }}"

Example: 例:

myApp.directive('ajaxMessage', function() {

  return {
    restrict: 'EA',
    scope: {
      success: '='
    },

    // Use anything you like in the template -- note the ng-if will only
    // render the element when the success property has a value
    // Also note the {{ binding }}

    template: "<div ng-if=\"success\" class=\"alert alert-info\">{{ success }}</div>",

    link: function($scope, $element, $attrs) {

      // Watching $scope.success (not the $attrs.success)

      $scope.$watch('success', function(value) {
        console.log('Success is now:', value);  
      });
    }
  };

});

... or see this plunker in action. ...或者看到这个小家伙正在行动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM