我一生无法解决这个问题。我什至不知道这是AngularUI Router还是Ionic本身的问题。

我正在尝试使用自定义AngularJS指令完成双向绑定(即指令定义中的scope: {data: "="}),它可以完美地工作,如this jsfiddle所示,但在我的特定上下文中使用的是完全相同的代码(即:我导航通过两个状态进入“更改数据”按钮之前,页面没有显示(jsfiddle here)。

SO提示我添加一些代码以沿jsfiddle链接移动,因此这里是工作版本。

页:

<!-- HTML -->
<body ng-app="myApp">
    <div ng-controller="MyCtrl">
        <signature data="signatureData"></signature>
        <button ng-click="changeData()">Change data!</button>
    </div>
</body>


脚本:

//JS
angular.module("myApp", [])
.controller("MyCtrl", ["$scope", function ($scope) {
    $scope.changeData = function() {
        console.log("Outside directive:", $scope.signatureData);
        $scope.signatureData = "hello";
    };
}])
.directive("signature", [function() {
    var directiveDefinitionObject = {
        template: "<div>Don't mind me, I'm just a template...</div>",
        scope: {
            data: "="
        },
        controller: ["$scope", "$element", function($scope, $element) {
            $scope.data = "ciao";
            $scope.$watch("data", function(d) {
                console.log("Inside directive:", d);
            });
        }]
    };
    return directiveDefinitionObject;
}]);

/* Console output when clicking button:
Inside directive: ciao
Outside directive: ciao
Inside directive: hello
*/


相同的代码虽然放在上下文中,但在第二个小提琴中太冗长了,无法在此处粘贴(对此我表示歉意,我已经尽可能地略过了,但只是为了对问题有所了解,以防它有所帮助)。

但是,控制台输出为:

/* Console output when clicking button:
Inside directive: ciao
Outside directive: undefined
*/

最佳答案

在调用$ scope.signatureData =“ hello”之前,未定义$ scope.signatureData;

转到该控制器时,尝试定义signatureData ...

.controller("JobRegistrationCtrl", ["$scope", function ($scope) {
    $scope.signatureData = "ciao"; //Now it's defined
    $scope.changeData = function() {
        console.log("Outside directive:", $scope.signatureData);
        $scope.signatureData = "hello";
    };
}])

09-28 10:57