双向绑定Angularjs指令不起作用

时间:2013-10-01 16:58:41

标签: angularjs-directive angularjs-scope

我一直试图找出解决方案,但我认为我走到了尽头。

所以这是我的指示

directives.directive('postprocess', function($compile)
{
    return {
        restrict : 'E',
        require: '^ngModel',
        scope: {
            ngModel: '='
        },
        link: function(scope, element, attrs) {
            var parsed = scope.ngModel;
            el = $compile(parsed)(scope);
            element.html("");
            //add some other html entities/styles.
            element.append(el);
            console.log(parsed);
        }  
    };
});

html

<postprocess ng-model="some_model.its_property" style="padding-top: 10px;" />

在控制器的某处,我更新了模型属性

some_model.its_property = 'Holla';

但它没有更新相应的指令。它在加载时非常有效,它告诉我它可能不完全是一个范围问题。

3 个答案:

答案 0 :(得分:15)

它更简单,所以我删除了你在那里的一些额外代码。

请查看以下代码或使用Plunker

<!doctype html>
<html lang="en" ng-app="myApp">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>

    <script>
        var myApp = angular.module('myApp', []);
        myApp.directive('postprocess', function ($timeout) {
            return {
                restrict : 'E',
                transclude: 'true',
                scope: {
                    myVariable: '='
                },
                link: function(scope, element, attrs) {
                    $timeout(function () {
                        scope.myVariable = 'Bye bye!'
                    }, 200);
                }  
            };
        });

        myApp.controller('myAppCtrl', ['$scope', '$timeout', function ($scope, $timeout) {
            $scope.myVariable = {
                value : 'Holla'
            };

            console.log($scope.myVariable.value); // -> prints initial value
            $timeout(function () {
                console.log($scope.myVariable.value); // -> prints value after it is changed by the directive
            }, 2000);
        }])
    </script>

    </head>
    <body ng-controller="myAppCtrl">
        <postprocess my-variable="myVariable.value" style="padding-top: 10px;" />
    </body>
</html>
  1. 控制器将初始值设置为“Holla”
  2. 该指令通过my-variable属性
  3. 接收该值
  4. 使用双向数据绑定对scope.myVariable所做的任何更改都会更新主控制器的$scope.myVariable
  5. 几秒后$scope.myVariable更改为“再见”
  6. 看看你的console.log
  7. $ watch和$ apply

      

    Angular的双向数据绑定是Angular中所有令人敬畏的根源。然而,这并不神奇,在某些情况下你需要在正确的方向上轻推。

         

    使用ng-model,ng-repeat等将值绑定到Angular中的元素时,Angular会在该值上创建$ watch。然后,只要范围上的值发生更改,所有$ watch都会执行观察该元素,并且所有内容都会更新。

         

    有时,通常在编写自定义指令时,您必须在范围值上定义自己的$ watch,以使指令对更改做出反应。

         

    另一方面,有时您会在某些代码中更改范围值,但应用程序不会对其做出反应。在代码片段运行完毕后,范围变量的角度检查会发生变化;例如,当ng-click调用范围上的函数时,Angular将检查更改并做出反应。但是,有些代码在Angular之外,你必须调用scope。$ apply()自己来触发更新。这在自定义指令中的事件处理程序中最常见。

答案 1 :(得分:1)

来自angularjs irc,&amp;的一些帮助dluz,更新。虽然我希望有一个更简单的方法来调用该指令,因为链接函数包含行为,应该有一种方法来调用它。

http://jsfiddle.net/T7cqV/5/

答案 2 :(得分:1)

相关问题