Two way binding, shallow $watch, isolate scope not working together

前端 未结 1 1286
别那么骄傲
别那么骄傲 2021-02-05 14:52

Please refer to this fiddle for the questions. http://jsfiddle.net/AQR55/

1) Why a watch that is attached to an isolate scope property - which is bidirectionally bound t

相关标签:
1条回答
  • 2021-02-05 15:13

    Question 1.
    Since you are adding a item to the acts array, you need to set the third parameter in $watch() to true

    $scope.$watch('acts', function (neww, old) {
        console.log(neww)
    }, true);
    

    Demo: Fiddle

    Question 2.
    Since there is an isolated scope, you need to call the $parent scope's function

    <input type="button" bn="" acts="acts" ng-click="$parent.addaction()" value="Add Action" />
    

    Demo: Fiddle

    Question 3.
    Yes you can, but you need to use a controller

    animateAppModule.directive('bn', function () {
        return {
            restrict: "A",
            scope: {
                acts: '='
            },
            link: function ($scope, iElement, iAttrs) {
                $scope.$watch('acts', function (neww, old) {
                    console.log(neww)
                }, true)
            },
            controller: function($scope){
                $scope.dosomething = function(){
                    console.log('do something')
                }
            }
        }
    })
    

    Demo: Fiddle

    An overall solution could look like

    <input type="button" bn="" acts="acts" addaction="addaction()" value="Add Action" />
    

    JS

    animateAppModule.controller('tst', function ($scope) {
        $scope.acts = [];
        $scope.addaction = function () {
            $scope.acts.push({
                a: "a,b"
            })
        }
    })
    
    animateAppModule.directive('bn', function () {
        return {
            restrict: "A",
            scope: {
                acts: '=',
                addaction: '&'
            },
            link: function ($scope, iElement, iAttrs) {
                $scope.$watch('acts', function (neww, old) {
                    console.log(neww)
                }, true);
                iElement.click(function(){
                    $scope.$apply('addaction()')
                })
            }
        }
    })
    

    Demo: Fiddle

    0 讨论(0)
提交回复
热议问题