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

Vla*_*kic 0 javascript angularjs

这是我的指示:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

并在HTML中:

<ajax-message success="vm.message"></ajax-message>
Run Code Online (Sandbox Code Playgroud)

问题是范围内的指令我从vm.message(它是我的控制器var)得到初始消息但是当我的vm.message更改它没有在指令中检测到...而且我想模板显示只有我从中获得成功消息vm.success.有谁知道怎么做到这一点?谢谢

nul*_*ull 5

  1. 你把错误的论点传给了$watch.它应该是一个表达式 - 而不是attrs对象的价值.
  2. 您可以使用该ng-if指令来控制可见性.
  3. 不确定这是否有意,但成功模板可能需要卷曲绑定: "{{ success }}"

例:

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

});
Run Code Online (Sandbox Code Playgroud)

......或者看到这个羽毛球在行动.