Angular指令模型绑定

时间:2015-03-17 22:17:58

标签: angularjs angularjs-directive

我刚刚发现了AngularJS,而且我的学习曲线似乎相当陡峭。任何人都可以推荐一些好书,这些书会带来一些实用的"深入AngularJS。我的编程问题是:

考虑:

<input type="text" name="inputField1" ng-model="myModel.firstName" 
       encrypt-and-save="myModel.encryptedFirstName" /> 

在我的指令中命名为&#34; encryptAndSave&#34;我想动态绑定到名称(在本例中)是&#34; encryptedFirstName&#34;的模型属性。我读过的所有内容似乎都说这是可能的,但我还没有找到一个具体的例子来说明它是如何完成的。任何帮助/指针将不胜感激。

提前致谢, 吉米

这是我最后做的事情。我发现了$ parse和.assign。我在初始化时使用$ parse,在后期/实时绑定中使用.assign。这是否有意义,或者我完全错过了什么?

app.directive('encryptAndSave', function($parse) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ctrl) {
            var encryptedModelValue = $parse(attrs.encryptAndSave);
            //
            // wait for model change (could also wait for blur??)
            //
            scope.$watch(attrs.ngModel, function(newValue, oldValue) {
                var encrValue = encryptThis(newValue);
                encryptedModelValue.assign(scope, encrValue);
            });
        }
    };
});

再次感谢您的帮助, 麦

2 个答案:

答案 0 :(得分:0)

在你的指令中创建隔离范围并通过'='

使用双向绑定
scope: {
      encryptAndSave: '='
    }

请参阅下面的演示

var app = angular.module('app', []);

app.controller('firstCtrl', function($scope) {
  $scope.myModel = {
    firstName: "joe",
    encryptedFirstName: " encrypted joe"

  };
});

app.directive('encryptAndSave', function() {
  return {
    scope: {
      encryptAndSave: '='
    },
    link: function(scope, elem, attr) {


      alert(scope.encryptAndSave)
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app">
  <div ng-controller="firstCtrl">
    <input type="text" name="inputField1" ng-model="myModel.firstName" encrypt-and-save="myModel.encryptedFirstName" />
  </div>
</body>

答案 1 :(得分:0)

我是关于这个的观察者。原因是您无法使用隔离范围访问父作用域的动态成员。我可能错了,但看起来这就是你想要做的事情。

angular.module("encryptMe", [])
.directive("encryptAndSave", function() {
    function hash(name) {
        return name;
    }

    return {
        link: function(scope, element, attrs) {
            scope.$watch("firstName", function() {
                scope[attrs.encryptAndSave] = hash(scope.firstName + "");
            });
        }
    };
})
.controller("encryptController", function($scope) {
    $scope.firstName = "Who?";
});

当然,您希望hash函数中有更多有趣的内容。这里的主要内容是该指令关注声明指令(encrypt-and-save=[your variable here])时传递的值。然后,它会监视firstName变量,并使用新值的哈希值更新给定的父范围变量。

随意try it in a fiddle

相关问题