指令对属性变化做出反应

时间:2016-01-01 22:34:21

标签: angularjs

我有一个带有属性的指令:

html:

<my-directive id="test" myattr="50"></my-directive>

js:

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

    var link = function(scope, element, attrs) {

        scope.$watch('myattr', function(value) {
            element.attr('myattr', value);
        });

        scope.change = function() {
            // some code
        };
    };

    return {
        restrict: 'E',
        template: '<input type="text" ng-change="change()" ng-model="myattr"/>',
        scope: {myattr: '='},
        link: link
    };
});

我的目标是保持myattr并且输入的值相等。使用element.attr('myattr', value)我可以强制myattr拥有正确的值,但在myattr更改时我应该如何更新输入?

例如,在这个jsfiddle中,当点击按钮时,我会尝试:

$('#test').attr('myattr', Math.random() * 100);

但我无法找到一种方法来捕捉&#39;指令内的变化。

我想帮助修改jsfiddle,以便:

  1. 在jquery调用之后调用函数change
  2. 输入值始终等于myattr

1 个答案:

答案 0 :(得分:0)

您需要将myattr的值作为属性存储在范围上,而不是作为属性的值。

您的指示是正确的,您还需要连接控制器。

&#13;
&#13;
var myApp = angular.module('myApp', []);

myApp.controller('MainController', function ($scope) {
    $scope.calculate = function () {
    // your logic here
    alert($scope.val);
  }
});

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

  var link = function(scope, element, attrs) {
    
    scope.change = function() {
      console.log("change " + scope.myattr);
    };

  };

  return {
    restrict: 'E',
    template: '<input type="text" ng-change="change()" ng-model="myattr"/>',
    scope: {
      myattr: '='
    },
    link: link
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">

  <div ng-controller="MainController">
    My Value: {{val}} <br/>

    <button type="button" ng-click="calculate()">ok</button>
    <my-directive id="test" myattr="val"></my-directive>    
  </div>


</div>
&#13;
&#13;
&#13;

相关问题